我在下面的代码中遇到了问题。当我输入任何整数,例如
更清楚的问题是:为什么它在失败后不等待?
(0-9)
,那么它就可以正常运行。但是当我输入其他字符,例如 A
、B
或任何其他字母时,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;
}
}
}
更清楚的问题是:为什么它在失败后不等待?
int
)并且能够处理任意长度的垃圾输入的优点。 - zwol