如何处理杂散字符输入,如下面的代码片段所示
#include <stdio.h>
int main ()
{
int i, j=0;
while (j <3)
{
printf("\n Enter the number to be displayed ");
scanf("%d",&i);
printf("\n The number to be displayed is %d \n", i);
j++;
}
return 0;
}
输出
philipa@hq1-up-swe-01{1436}: ./a.out
Enter the number to be displayed 45/
The number to be displayed is 45
Enter the number to be displayed
The number to be displayed is 45
Enter the number to be displayed
The number to be displayed is 45
这里&#39; /&#39;是错误添加的。我想冲洗这个&#39; /&#39;在它作为下一个循环的输入之前。我该如何处理这种情况?
答案 0 :(得分:2)
您可以使用单一循环
int c;
while((c=getchar()) != '\n' && c != EOF);
它将清除输入缓冲区。将其放在scanf之后。
while(1)
{
switch(opt)
{
...
...
...
}
while((c=getchar()) != '\n' && c != EOF); // It will clear the buffer before getting the next value.
}