scanf() 用于整数或字符 [英] scanf() for Integer OR Character

查看:51
本文介绍了scanf() 用于整数或字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 while 循环,当条件isDone"设置为 true 时该循环将结束.在 while 循环中,我要求用户输入一个整数来继续循环或输入一个字符来结束它(通过将isDone"设置为 true).

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

我将如何仅使用 one scanf() 来解决这个问题?

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

推荐答案

上面的建议是很好的建议:您可能最好不要使用 scanf().最好使用类似 fgets() 之类的东西,然后解析字符串.或者甚至更好,只需使用 getchar().

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

不过……

请记住,在 C 中,字符" 一个整数.所以只需 scanf("%c", &i) 并检查您是否有一个整数"(isdigit()) 或字符"(isalpha()).

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

这篇关于scanf() 用于整数或字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆