Search code examples
carraysgetchar

replacing integers with strings in C


I wrote code that replaces integers from 0 to 3 with strings. I was only allowed to use getchar() and putchar(). If the input is 1, the output will become "one".

#include <stdio.h>

int main()
{
    int c;            
    char* arr[4] = {"zero", "one", "two","three"};
    int i;

        while ((c = getchar ()) != EOF) 
        {
            if(c==0+'0') {
                char* str = arr[0];
                for (i = 0; str[i] != '\0'; i++) {
                    putchar(str[i]);
                }
            }
            else if(c==1+'0') {
                char* str = arr[1];
                for (i= 0; str[i] != '\0';i++) {
                    putchar(str[i]);
                }
            }
            else if(c==2+'0') {
                char* str = arr[2];
                for (i = 0; str[i] != '\0'; i++) {
                    putchar(str[i]);
                }
            }
            else if(c==3+'0') {
                char* str = arr[3];
                for (i = 0; str[i] != '\0'; i++) {
                    putchar(str[i]);
                }   
            }
            else
                putchar(c);
   }

return 0;
}

The code is pretty long. Is there a shorter way to write it?

If I type in 33 the output will be "threethree". Could anyone give me suggestions how can i modify my code not to do that?

note: I am also not allowed to use functions.


Solution

  • You can use a variable to remember last input and compare, so that you will not print continuous char.

    #include <stdio.h>
    
    int main()
    {
        int c;
        char* arr[4] = {"zero", "one", "two","three"};
        int i;
        char last_input = '9';
    
        while ((c = getchar ()) != EOF)
        {
            if(c != last_input && '0' <= c  && c <= '3') {
                last_input = c;
                int index = c - '0';
                char* str = arr[index];
                for (i = 0; str[i] != '\0'; i++) {
                    putchar(str[i]);
                }
            }
            else{
                putchar(c);
            }
    
        }
        return 0;
    }