我在我的代码下面遇到问题。当我输入任何整数,即(0-9)
,那么它是确定的。但是,当我输入其他字符如A
,B
或任何其他字母scanf()
失败。然后它不会等待任何进一步的输入。为什么scanf在一次失败后不等待用户输入?
我附上了一个代码片段。我非常需要仅使用C标准库的错误处理。
#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;
}
}
}
更清楚的问题是:为什么在失败后等待?
这工作正常,但是C库提供了一些设施来清除输入缓冲区。就像它们为输出缓冲区提供像fflush()一样的工具。 – rajesh6115 2012-08-04 02:44:13
不,没有标准的工具来清除输入缓冲区(尽管有些实现可能提供它)。只要阅读输入,例如使用fgets()。这只是一个像fflush()一样的函数调用。 – nos 2012-08-04 02:48:02
谢谢你的回答... – rajesh6115 2012-08-04 02:53:22