0

我需要接收数字,直到按回车键,我试图将 scanf 的返回值与 EOF 进行比较,但它一直要求我输入更多数字(无限循环):

int fail=0, late=0, avg=0, i=0, last=0, current, permission, difference;
while(scanf(" %d", &current) != EOF)
{
    permission = (current < last);
    difference = ((last - current) >= 30);
    fail += difference*permission;
    late += permission;
    avg += (last - current)*(permission);
    last = last*(permission) + current*(!permission);
}

有什么建议么。
谢谢

4

3 回答 3

0

One issue you are having is that the documentation for scanf says that most format conversions skip whitespace. (This includes carriage return and newline.)

One option is to read a character at a time and then make some numbers. In this way you could catch any bogus input. You could also differentiate between inline whitespace (space and tabs) and line terminating whitespace (CR and NL).

于 2012-05-05T20:20:59.313 回答
0

如果您使用的是 linux,您可以在输入时停止您的 while 循环CTRL+D

EOF = CTRL+ D(对于 Linux)

EOF = CTRL+ Z(对于 Windows)

于 2012-12-31T13:41:33.460 回答
0

好吧,scanf 规范说它将读取并忽略任何空白字符。此外,规范说只有在输入失败的情况下才会返回 EOF,然后才能成功读取任何数据。你可以在这里自己阅读。

我建议使用其他答案中提到的其他阅读功能。尽管如此,如果您必须在该 scanf 循环中生存和死亡,也许您可​​以在底部添加以下代码:

if (getchar() == '\n') break;

如果您的输入只是数字,它应该可以工作,并且它只是使其工作的一种方法。

于 2012-05-06T01:57:11.713 回答