0

The code is given below :

#include <stdio.h>
#include <string.h>

int indexFinder(int num, int array[])
{
    int index;
    for (int i = 0; i < 21; i++ )
    {
        if (num - array[i] < 0)
        {
            index = i - 1;
            break;
        }
    }
    return(index);
}


int main()
{   
    //  Required information for translation :
        //  User Input
    int num ;
        //  Data
    int  reqNum[21]    = {1,4,5,9,10,40,50,90,100,400,500,900,1000,4000,5000,9000,10000,40000,50000,90000,100000};
    char romSym[21][6] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M", "M_V", "_V", "M_X", "_X", "_X_L", "_L", "_X_C", "_C"};
    
    //  Asking for user input
    printf("Enter a number: ");
    scanf("%d", &num);
    
    // Main Running Code
    char translation[30];
    int ind;
    while (num > 0)
    {
        ind = indexFinder(num, reqNum);
        strcat(translation, romSym[ind]);
        num -= reqNum[ind];
    }
    
    printf ("%s", translation);
    
    return 0;

}

Output

Enter a number: 23456
�n��_X_XMMMCDLVI

The extra characters appearing is because of using strcat() as i assumed at first. But after making my own function to add two string it still had the same issue.

Similar code in python works just fine but here.

Please help

1 Answers1

3

strcat works on the assumption that your destination string is null-terminated.

You need to initialize your string to null-bytes - char translation[30] = {0};.


For future reference - usually, when you see "garbage characters" like �n��_X_XMMMCDLVI - it's a sign that something was corrupted in your string. You could have debugged this by e.g. printing your translation string in every iteration of the while loop and seeing how it changes - you would have seen on the very first iteration that it's full of garbage bytes, and on the next iteration that strcat only appends after the garbage bytes - which should be enough to give you a very strong clue.

Daniel Kleinstein
  • 5,262
  • 1
  • 22
  • 39