[英]Requesting int input, how to guard against char?
I'm asking for int input, and then checking whether it is equal to the correct answer, but how do I guard against users inputting chars? 我要求输入int,然后检查它是否等于正确的答案,但是如何防止用户输入字符?
int main()
{
int response;
int answer;
scanf("%f", &response);
if(response == answer)
{
//Correct!
}
else
{
//Incorrect!
}
}
scanf(3) gives a result (the count of successfully read items), that you should use. scanf(3)给出您应该使用的结果(成功读取项目的计数)。 And your
%f
is incorrect, so you should code 而且您的
%f
不正确,因此您应该编写代码
if (scanf(" %d", &response)==1) {
/// did got some response
}
I took into account the good comment of Jonathan Leffler in the answer of Soumya Koumar ... 我考虑了好评论的乔纳森·莱弗勒在Soumya Koumar的答案 ...
You will have to use %d
for scanning an int from input. 您将必须使用
%d
从输入扫描int 。
According to scanf
definition it returns the number of items scanned if successful or 0 in case there is a matching failure. 根据
scanf
定义,如果成功则返回扫描的项目数,如果匹配失败则返回0。 So if you enter a char instead of an integer in the standard input it will return 0 as the return value. 因此,如果在标准输入中输入char而不是整数 ,则它将返回0作为返回值。
You can do something like: 您可以执行以下操作:
if (scanf(....) == 0) {
/* error */
} else {
/* do my work */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.