scanf() for Integer OR Character

2019-08-31 08:49发布

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()?

标签: c scanf
1条回答
看我几分像从前
2楼-- · 2019-08-31 09:36

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()).

查看更多
登录 后发表回答