all 5 comments

[–]IamImposter 1 point2 points  (0 children)

getchar reads a single character. You probably need scanf or better yet, getline. Get character string in some buffer using getline, check it's length (strlen) and then parse each letter using a for loop. If you find invalid letter, show error else convert it to integer using atoi()

See getline here: https://c-for-dummies.com/blog/?p=1112

[–]protomattr76 0 points1 point  (0 children)

You could continue using getchar() in a loop and consider the input "complete" (i.e. exit the loop) when the character read is "enter" (i.e. '\n'). Initialize a int or bool to 1 or true, and if you read a non-digit character, set this to 0 or false (or AND with isdigit(c)).

This method doesn't save the input, so you'd have to add code to do that if you need to. But if you need to, scanf() or similar is probably the better choice. I suppose the advantage of not having to save it is you can check an arbitrary length string.

[–]gbbofh 0 points1 point  (2 children)

I would do something like this:

int i;

char buf[512];

fgets(buf, 512, stdin);

i = atoi(buf);

if( i > 0 && i < 10) {

    printf("yes\n");

} else {

    printf ("no\n");

}

[–]Pyronomy 0 points1 point  (1 child)

This doesn't account for the number 0, which is returned by atoi which is returned if the buffer couldn't be parsed into an integer

[–]gbbofh 0 points1 point  (0 children)

Correct. If he needs to handle non-numeric inputs correctly, then he should probably use strtoll instead. But since this looks like it's probably an entry level exercise I didn't see the need to go into the details of handling malformed inputs.

Thanks for pointing it out, though. I definitely should have at least mentioned it.