سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top