Reputation: 167
I use scanf to read the input from stdin
since scanf is considered much faster than cin
. I found the following unexpected behavior:
for(int i = 0; i<3; i++) {
scanf("%d ", &t);
printf("The input was %d\n", t);
}
The "%d "
format in scanf
is expected to read an integer and ignore the white-space or new-line characters after it. Hence the expected output should be something like:
0
The input was 0
1
The input was 1
2
The input was 2
However I get the follwing output:
0
1
The input was 0
2
The input was 1
Could someone please help me understand the behavior here?
Upvotes: 2
Views: 73
Reputation: 399713
Put the space before the %d
. Or, even better, remove it!
Also, check the return value of scanf()
before relying on t
having a valid value.
Upvotes: 1
Reputation: 108968
When you type 1ENTER
the library code sees the 1
and matches it to "%d"
. Then it sees the ENTER
and starts matching that to " "
. As nothing else gets in, it waits and waits and waits.
After a while you type 2ENTER
. Since scanf()
is still waiting for whitespace and 2
is not whitespace the call terminates successfuly, leaving the 2
in the buffer and printing "The input was 1"
.
and so on ...
So, do not put spaces at the end of the conversion specification -- or anywhere else since most conversion specification already do leading whitespace suppresion.
Upvotes: 5