how use EOF stdin in C

大憨熊 提交于 2019-12-03 16:00:53

I suggest using

while(!feof(stdin) && scanf ( "%d %d ", &a, &b) == 2)

and actually it is better to test feof after (not before!) some input operation, so:

while (scanf("%d %d ", &a, &b) == 2 && !feof(stdin))

BTW, on many systems stdin is line buffered, at least with interactive terminals (but perhaps not when stdin is a pipe(7)), see setvbuf(3)

On Linux & POSIX you might consider reading every line with getline(3) (or even with readline(3) if reading from the terminal, since readline offers editing abilities), then parsing that line with e.g. sscanf(3) (perhaps also using %n) or strtol(3)

The only real problem that I see in your code is the extra spaces in the scanf format string. Those spaces tell scanf to consume whitespace character on the input, which makes scanf not return to your code until it hits a non-whitespace character (such as a letter, a number, punctuation, or EOF).

The result is that after typing two numbers and then Enter, you have to type Ctrl-D (Ctrl-Z in DOS/Windows) twice before your program escapes the while loop.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!