while循环中的scanf函数[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

以下代码的输出对我来说非常奇怪。任何人都可以解释一下为什么它的表现如此?

#include<stdio.h>
int main()
{
    int i=0;
    char ch='a';

    while(ch!='q')
    {
       scanf("%c",&ch);
       printf("\t%d\n",i);
       i++;
    }

}

产量

enter image description here

c while-loop scanf
1个回答
0
投票

在你的scanf声明之后写下这个声明。

while( getchar() != '\n' );  /* flush to end of input line */

下一次循环执行时,它会自动从standard input buffer中获取字符,所以你必须在每个scanf之后清除它,这样它就不能用于下一个scanf。这是由我上面的代码行完成的。

© www.soinside.com 2019 - 2024. All rights reserved.