我必须让用户输入数字/百分比对。代码如下:
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
}
}
通过这种方式,您不需要临时的 line
和 percent_line
缓冲区。 fscanf()
函数将自动继续读取输入,直到它得到它正在寻找的内容 - 这意味着如果您只是在“输入数字”提示时按 Enter,fscanf()
函数不会返回并会继续读取输入,直到您键入一个数字。另外,上面没有实现错误处理,我把它留给读者作为练习,以解决当您输入不是数字的内容时发生的问题。
(请注意,我还将 choice
更改为 &choice
,我认为您一开始就打算这样做。)
关于c - 在每个整数输入后刷新 c 输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/479099/