为什么不scanf函数等待用户输入失败一次后? [英] why does scanf not wait for user input after it fails one time?
问题描述
我在下面code面的问题。当我输入任意一个整数,也就是(0-9)
,那么它是确定。但是,当我输入一些其他的字符,如 A
, B
或任何其它信 scanf()的
失败。然后,它不会等待任何进一步的输入。
I face problem in my code below. When I enter any integer, that is (0-9)
, then it is OK. But when I enter some other characters like A
, B
or any other letter scanf()
fails. Then it doesn't wait for any further input.
我已经附加了这个$ C $ C片段。我强烈要求只使用C标准库的错误处理。
I've attached a code snippet for this. I highly require error handling using only the C standard library.
#include <stdio.h>
int main()
{
int choice;
while(1)
{
printf("Enter your choice: ");
if(0 == scanf("%d", &choice))
{
printf("Some error occured\n");
//break;/*I did not want to break this loop as I use this to show menu*/
}
switch(choice)
{
case 0:printf("Case 0\n");break;
case 1:printf("Case 1\n");break;
case 2:printf("Case 2\n");break;
case 3:printf("Case 3\n");break;
case 4:printf("Case 4\n");break;
case 5:printf("Case 5\n");break;
case 6:printf("Case 6\n");break;
case 7:printf("Case 7\n");break;
case 8:printf("Case 8\n");break;
case 9:printf("Case 9\n");break;
default:printf("Default case\n");break;
}
}
}
问题更清楚的是:为什么没有失败后等待
Question more clearly is: why doesn't it wait after failure?
推荐答案
通过 scanf函数
,如果给定的输入不符合格式规范,则输入ISN吨消耗并保持在输入缓冲器。换言之,不匹配的字符从不读
With scanf
, if the input given doesn't match the format specification, then the input isn't consumed and remains in the input buffer. In other words, the character that doesn't match is never read.
所以,当你输入,例如一个<大骨节病> A 骨节病>字符,你的code将无限循环为 scanf函数
继续失败的相同的字符。
So when you type, e.g. an a character, your code will loop indefinitely as scanf
continues to fail on the same character.
在 scanf函数
返回一个错误,你需要摆脱违规字符(县)的。
When scanf
returns an error, you need to get rid of the offending character(s).
您无法知道有多少字符将被输入,而是一个简单的方法来消耗任何违规的字符是尝试读取字符串时scanf函数失败:
You can't know how many characters will be typed, but one simple way to consume any offending characters is to try and read a string when scanf fails:
char junkChars[256];
printf("Enter your choice: ");
if (scanf("%d", &choice) == 0)
{
printf("Some error occured\n");
scanf("%s", junkChars);
}
这将清除输入缓冲区,但依赖于一个上限。如果用户键入更多的超过256个字符,在 scanf函数
将继续消耗他们的下一次迭代(S)。
This will clear the input buffer, but relies on an upper-bound. If the user types more than 256 characters, the scanf
will continue to consume them on the next iteration(s).
显然,这是一个丑陋的解决方案,但 scanf函数
是不是真的因为这个原因有很大的投入机制。最好使用与fgets
来获得输入行作为一个字符串,然后控制该字符串的解析自己。
Clearly this is an ugly solution, but scanf
isn't really a great input mechanism for this reason. Better to use fgets
to get the input line as a string, then control the parsing of that string yourself.
这篇关于为什么不scanf函数等待用户输入失败一次后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!