在执行代码块时,它跳过字符输入,即scanf()



每次我尝试运行代码时,字符输入语句scanf("%c",&ch(;被完全忽略并跳到netx行,导致执行无限while循环(我在上面的块中让它成为注释行(。找不到我哪里出错了。不过,其他功能运行正常。

void main()
{
int n,g,i;
char ch;
printf("Enter the number of students present todayn");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the rolls of the students who are presentn");
attendance();
}
printf("Enter the state of the student entry/departuren");
printf("n a for Entry and d for departure and c for door closen");
scanf("%c",&ch);

/*while(1)
{
switch(ch)
{
case 'a':
printf("Enter the roll of the students who arrivedn");
entry();
break;
case 'd':
printf("Enter the roll of the student who departedn");
departure();
break;
case 'c':
exit(0);
default:
printf("Wrongn");
}
}*/
printf("Want to see the rolls of the student left in class?[1/0]");
scanf("%d",&g);
if(g==1)
display();
}

是的,scanf可能很棘手。要调试这样的问题,在scanf后面插入一行可以很有帮助地显示结果,比如:

printf("scanf got character '%c' (0x%02x)n", ch, ch);

这将向您显示该字符和该字符的数值,如果该字符是一种异国情调的东西,并且没有易于识别的打印外观,这将非常有用。

如果你在这种情况下这样做,它会告诉你scanf("%c")给了你它找到的下一个字符,那就是换行符。这是仍然位于输入缓冲区中的换行符,是attendance函数中上一次scanf调用检查的输入行末尾留下的。

如果您希望scanf跳过剩余的空白字符,包括换行符,那么您应该在scanf格式字符串的开头放一个空格。所以改变你现有的:

scanf("%c",&ch);

scanf(" %c",&ch);

这会让你得到你想要的行为。

最新更新