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?