The program only appears to accept 4 inputs into scanf()
.
int a,b,c;
scanf("%d\n%d\n%d\n",&a,&b,&c);
With each "%d
, scanf()
reads
1) any leading white-space including ' '
and '\n'
and other white-space then
2) it reads in the digits to form the int
until it reads a non-digit, usually the \n
.
3) This extra char
is put back into stdio
for subsequent scanning.
The \n
tells scanf()
to read in, and not save, any number of white-space, not just only '\n'
. Reads will continue until a non-white-space is read. That non-white-space is put back into stdio
for subsequent scanning.
So with 3 sets of "%d\n"
, once needs to enter the below for scanf()
to read 3 ints
and complete.
optional-white-space (+-)[1 or more 0-9] optional-white-space
optional-white-space (+-)[1 or more 0-9] optional-white-space
optional-white-space (+-)[1 or more 0-9] optional-white-space 1-non-white-space
Remember the non-white-space was put back for subsequent I/O. This short program never tried reading it again.
Since stdin
is typically buffered, that last non-white-space
needs a following \n
before the console gives the line to stdin
.
The best way to handle user I/O is to first get the line of text with fgets()
, then use sscanf()
, strtol()
, strtof()
or strtok()
to parse the received line.
// Example reading 1 `int` per line
int a[3];
for (int i=0; i<3; i++) {
char buf[40];
if (fgets(buf, sizeof buf, stdin)== NULL) Handle_EOForIOError();
if (sscanf(buf, "%d", &a[i]) != 1) Handle_ParseError();
}