这个问题在这里已有答案:
以下代码的输出对我来说非常奇怪。任何人都可以解释一下为什么它的表现如此?
#include<stdio.h>
int main()
{
int i=0;
char ch='a';
while(ch!='q')
{
scanf("%c",&ch);
printf("\t%d\n",i);
i++;
}
}
产量
在你的scanf
声明之后写下这个声明。
while( getchar() != '\n' ); /* flush to end of input line */
下一次循环执行时,它会自动从standard input buffer中获取字符,所以你必须在每个scanf
之后清除它,这样它就不能用于下一个scanf
。这是由我上面的代码行完成的。