gpt4 book ai didi

c - while 循环中的 scanf 函数

转载 作者:行者123 更新时间:2023-11-30 16:37:21 31 4
gpt4 key购买 nike

以下代码的输出对我来说非常奇怪。有人可以解释一下为什么它会这样吗?

#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

最佳答案

将此语句写在 scanf 语句之后。

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

下一次循环执行时,它会自动从 standard input buffer 中获取字符。 ,因此必须在每次 scanf 后清除它,以便它不可用于下一次 scanf。这是通过我上面的代码行完成的。

关于c - while 循环中的 scanf 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47997002/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com