c - 在每个整数输入后刷新 c 输入流

标签 c

我必须让用户输入数字/百分比对。代码如下:

while(choice != 0)
{
  printf("enter number");
  fgets(line, sizeof(line), stdin);//sizeof(line) is 6
  sscanf(line, "%d\n", choice);
  if(choice > 0)
  {
    printf("enter percentage\n");
    fgets(percent_line, sizeof(percent_line), stdin);//sizeof(percent_line) = 7
    sscanf(percent_line, "%f", &percentage);
    //add to an array holding numbers vs percentages
  }
}

问题在于,如果我在第 5 行输入一个长于 6(或 5)的字符串,则剩余的字符串将进入第 10 行扫描的内容,如果我输入一个更长的字符串,即 7(或 6)第 10 行的字符,剩余的输入进入第 5 行的输入。我想销毁任何剩余的输入。我该怎么做?

最佳答案

这不一定是最好的解决方案,但另一种方法可能是使用 fscanf():

while(choice != 0)
{
  printf("enter number");
  fscanf(stdin, "%d", &choice);
  if(choice > 0)
  {
    printf("enter percentage\n");
    fscanf(stdin, "%f", &percentage);
    //add to an array holding numbers vs percentages
  }
}

通过这种方式,您不需要临时的 linepercent_line 缓冲区。 fscanf() 函数将自动继续读取输入,直到它得到它正在寻找的内容 - 这意味着如果您只是在“输入数字”提示时按 Enter,fscanf() 函数不会返回并会继续读取输入,直到您键入一个数字。另外,上面没有实现错误处理,我把它留给读者作为练习,以解决当您输入不是数字的内容时发生的问题。

(请注意,我还将 choice 更改为 &choice,我认为您一开始就打算这样做。)

关于c - 在每个整数输入后刷新 c 输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/479099/

相关文章:

c - 在线程不安全函数上使用锁定和复制

python - 如何使用struct.pack格式构造字节?

c - 在 C 中循环使 RScript 性能更高效

c - 如何使用 openssl API 读取 DER 格式的服务器证书?

c - 定义测试替身时如何避免多重定义

c - 如何在类 UNIX 系统中设置进程的优先级

C 两链表查找

c - 如何使用 exec() 命令运行 a.out

c - 使用 GCC 生成 a.out 文件格式

c - printf 中的空格填充不起作用