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?
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!There are many problems with this approach. (EOF not active until after trying to read, text input like 'A' creates infinite loop, etc.) Instead :