Number to word program

Viewed 32

I need to write a program that prints the lowercase English word corresponding to the number (e.g., one for 1, two for 2, etc.). If n>9, print: Greater than 9.

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

int main()
    {
    int n;
    scanf("%d", &n);
    
    char keySet[9][5] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
    
    if (n > 9)
    {
        printf("Greater than 9");
    }
    else
    {
        n -= 1;
        puts(keySet[n]);
    }
}

For a positive int n, do the following:

  • If [1 ≤ n ≤ 9] print the lowercase English word corresponding to the number (e.g., one for 1, two for 2, etc.)
  • If n>9, print Greater than 9

Behavior:

Input: 8

Output: eightnine

Desired behavior:

Input: 8

Output: eight


Basically, this is only happening with every string having 5 characters, to be exact.

Like "three" & "seven"

Behavior:

Input: 7

Output: seveneightnine


When variable char keySet is defined like char keySet[9][6] it works as expected...

Putting value more than 5 works but not 5 itself not clear about the issue

1 Answers

You aren't giving the compiler enough room to store the strings. The string "eight" needs to be stored in an array of size (at least) 6 so that there is room for the null terminator.

That is: char a[6] = "eight" is the same as char a[6] = {'e', 'i', 'g', 'h', 't', '\0' }; and char b[5] = "eight" is the same as char b[5] = { 'e', 'i', 'g', 'h', 't' };. In these cases, a is a properly null terminated string, but b is not a string and passing it to printf as the target of a %s format specifier is undefined behavior.

Fortunately, you can avoid this problem by letting the compiler count for you with something like:

char *keySet[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
Related