I am writing a program which convert decimal number to roman number. I use 4 arrays thousands
, hundreds
, tens
, units
to store digits in roman number, then copy each digit to res
array, I use str
pointer to track where the string in res
begin. When I test with input 128
, it prints out CXXVIIIIX
which must be CXXVIII
. I have tried to debug and got the result when tmp=8
is strlen(units[tmp-1]) = 6
, which means strlen
also counts IX
. And for some case like 3888
, the program prints out trash value.
This is my code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
#include <windows.h>
int main(){
int n=128;
char thousands[][4]={"M","MM","MMM"};
char hundreds[][5]={"C","CC","CCC","CD", "D", "DC", "DCC", "DCCC", "CM"};
char tens[][5]={"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
char units[][5]={"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
char res[16];
res[15]='\0'; //add nul to the last character of res array
char *str=res+14; //str tracks where the string start
int tmp;
//store roman digits in res array in reverse order,
//start from units->tens->hundreds->thousands
if (n!=0)
{
tmp=n%10;
if (tmp!=0)
{
str-=strlen(units[tmp-1]); //str steps back several address to store new digits
strncpy(str, units[tmp-1], strlen(units[tmp-1])); //use strncpy to copy without '\0'
}
n/=10;
}
if (n!=0)
{
tmp=n%10;
if (tmp!=0)
{
str-=strlen(tens[tmp-1]);
strncpy(str, tens[tmp-1], strlen(tens[tmp-1]));
}
n/=10;
}
if (n!=0)
{
tmp=n%10;
if (tmp!=0)
{
str-=strlen(hundreds[tmp-1]);
strncpy(str, hundreds[tmp-1], strlen(hundreds[tmp-1]));
}
n/=10;
}
if (n!=0)
{
tmp=n%10;
if (tmp!=0)
{
str-=strlen(thousands[tmp-1]);
strncpy(str, thousands[tmp-1], strlen(thousands[tmp-1]));
}
n/=10;
}
printf("%s", str);
return 0;
}
So why does this happen and how to fix it?
Any help would be appreciated.