gpt4 book ai didi

c - 尝试清除输入缓冲区时无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:27 27 4
gpt4 key购买 nike

好的,在阅读了前面的这些问题之后:

Alternate method for clearing input buffer in c

How to clear input buffer in C?

我想出了一段代码来清空输入缓冲区并计算缓冲区中有多少个值,然后返回这个数字。然后进行比较以检查该数目是否超过允许数目。

#include <stdio.h>
#include <stdlib.h>


int Empty();
int main()
{
double x;
int y=0;
while(y==0)
{
y=1;

if(scanf("%lf",&x)!=1 || Empty()>1) //checks if the value is acceppted
// and then attempts to empty
// the input buffer. I always expect
//at least 1 returned due to the
// EOF or '\n'
{
fprintf(stdout,"Invalid character(s) entered, please re-enter.\n");
y=0;
}
}
return(x);
}

int Empty()
{
int clearr,n=0;
do
{
n++;
}while((clearr=fgetc(stdin))!= EOF && clearr !='\n'); // If EOF or '\n' is reached
// it ends, returning the
//number of characters
return(n);
}

如果我然后运行该程序并输入 2 或 2.2 等,该数字将被接受并返回。

如果我输入 2a、或 2 a 或 2 2 等,它总是会捕获空格/字母/等并强制执行一个单循环以允许您尝试重新输入一个值

但是,如果首先输入有问题的项目,即 a,则会发生无限循环。

据我所知,这对我来说没有意义,当调用 fgetc(stdin) 时,它必须拉出一个字符或一个 EOF 来表示只输入了一项,结束循环。

最佳答案

在测试 if( A || B ) 中,如果 A 为真,则 评估 B。

因此,如果 scanf("%lf",&x)!=1 为真,则不会调用 Empty(),您的循环将永远继续。

这里的一个问题是您尝试同时做几件事,建议是:

  • 保持简单
  • 无副作用

所以 1) 扫描输入,2) 如果没问题继续,3) 如果没有刷新并重复。

关于c - 尝试清除输入缓冲区时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36021987/

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