C - read scanf until feof(stdin), don't output

2019-05-31 08:06发布

问题:

I am using the scanf() function in my program to scan an integer. The way I am doing it is:

while (!feof (stdin))
if (scanf("%d", &height) != 1) { puts("Wrong input!"); return 1; }

The problem is, that after actually doing EOF, I get the wrong input and return 1, due to the scanf not returning 1. How should I solve this issue?

回答1:

As the documentation for scanf states, it will return the number of items successfully matched and assigned. This can be the number of items you gave if completely successful or any number less than that, down to zero, if it failed to match input. In the event of EOF, it will return EOF. So, check for it!

int result = scanf("%d", &height);
if (result != EOF && result != 1) {
    // We've failed!
}


回答2:

There are many problems with this approach. (EOF not active until after trying to read, text input like 'A' creates infinite loop, etc.) Instead :

char buf[100];
while (fgets(buf, sizeof buf, stdin) != NULL) {
  if (sscanf(buf, "%d", &height) != 1) {
    puts("Wrong input!");
    return 1;
    }
  do_something(height);
}
return 0;


标签: c return scanf eof