One of the problems with scanf
and all of the formatted input functions is that terminals tend to operate in line mode or cooked mode and the API is designed for raw mode. In other words, scanf
implementations generally will not return until a line feed is encountered. The input is buffered and future calls to scanf
will consume the buffered line. Consider the following simple program:
#include <stdio.h>
int main() {
int a_number;
printf("Enter a number: ");
fflush(stdout);
while (scanf("%d", &a_number) != EOF) {
printf("you entered %d\n", a_number);
printf("Enter another number: ");
fflush(stdout);
}
return 0;
}
You can enter multiple numbers before pressing return. Here is an example of running this program.
bash$ gcc foo.c
bash$ ./a.out
Enter a number: 1 2 3 4 5 6 7 8 9 10<Return>
you entered 1
Enter another number: you entered 2
Enter another number: you entered 3
Enter another number: you entered 4
Enter another number: you entered 5
Enter another number: you entered 6
Enter another number: you entered 7
Enter another number: you entered 8
Enter another number: you entered 9
Enter another number: you entered 10
Enter another number: <Ctrl+D>bash$
bash$
Each call to scanf
read a single number from the input stream but the first call did not return until after I pressed return. The remaining calls returned immediately without blocking for more input because the input stream was buffered and it could read another integer from the stream.
The alternatives to this are to use fgets
and processing entire lines of data at one time or using the terminal interface to disable "canonical input processing". Most people use fgets
since the terminal interface section of POSIX is not implemented under Windows.