1
votes

For my homework I have to swap and int with a character. For example if the user types in 1 the output should be "one". this should work from zero to 5.

My Idea would be to implement a char array that looks like this.

*string[] = { "zero\0", ....., "five\0"}

Then I would implement it in a code like this.

#include <stdio.h>

int main() 
{
    int c; 
    while((c=getchar())!=EOF)
    {
        putchar(c);
    }

    return 0; 
}

So since I am only allowed to use putchar and getchar and no heap. This would be my approach: I would create a for loop that would print out the every letter until \0 is reached.

Is this the right approach?

1
This approach does not seem to use string at all. - Scott Hunter
1) string literals are already null-terminated, you shouldn't add another \0 at the end. 2) if i == 0, then string[i] will evaluate to "zero" (or, in your case "zero\0"). - Groo
@IncreasinglyIdiotic: the way I read it, OP wants to print one when the user types in 1. The string literal "one" already contains 4 characters, the last being '\0'. - Groo

1 Answers

0
votes

You are on the right track, but here are a few pointers.

I'm not sure what *string[] is, but because you know the size of your array ahead of time you can make a fixed size char* array to hold your strings like this

char* arr[6] = {"zero\0", "one\0", ..., "five\0"};

Notice the array has both a type (char*) and a name (arr).

Next you can read in the number you wish to print with

int c = getchar();

And you can use your previously defined array to get the correct string and loop over it printing it one char at a time with putchar

char* str = arr[c];
for (int i = 0; str[i] != '\0'; i++) {
    putchar(str[i]);
}
putchar('\n');

And as Groo pointed out string literals are implicitly null terminated so you son't need to include \0 on your strings. The array can just be

char* arr[6] = {"zero", "one", ..., "five"};

And everything will still work.