scanf() for Integer OR Character

2019-08-31 09:35发布

问题:

So let's say I have a while loop that will end when the condition "isDone" is set to true. Inside the while loop, I ask the user to either enter an integer to continue the loop or a character to end it (by setting "isDone" to true).

How would I go about this using only one scanf()?

回答1:

The suggestion above is good advice: you're probably better off not using scanf() at all. It might be better to use something like fgets() instead, and then parse the string. Or even better, just use getchar().

But anyway ...

Remember that, in C, a "character" IS an integer. So just scanf("%c", &i) and check if you've got an "integer" (isdigit()) or a "character" (isalpha()).



标签: c scanf