0

Today I wrote a program in which I used scanf(). The program was correct but when I debugged it, the program was waiting for input even though I hit enter and didn't display the result until I pressed another number/character and then hit enter again. At that moment it showed the calculated value of input. I examined my code and found that I had placed a space after the format specifier. When I removed the space it worked fine.

 `scanf("%d ",&a);`

What is the reason for this behavior?

Carey Gregory
  • 6,836
  • 2
  • 26
  • 47

2 Answers2

2

I/O is buffered and you need to flush it.

With <stdio.h> call e.g. fflush(NULL) or fflush(stdout). Read the fflush(3) and related man pages.

With C++ iostream do a cout << std::flush or cout.flush (or, as commented by jodag do a cout << std::endl which output a newline then flush). Read about std::flush etc..

And with scanf("%d ",&a) the reader has to get the non-digit character just after the number (perhaps space, or getting end-of-line or end-of-file). Read scanf(3) man page.

I do advise flushing the stdout before your scanf (that is sometimes, but not always, done automatically)

BTW, the prefered C++ way of inputting a number is probably

 std::cin >> a;
Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    It's also good to know that in c++, `std::cout << std::endl` is equivalent to `std::cout << '\n' << std::flush` – jodag Sep 19 '13 at 19:43
  • What does flushing stdout have to do with stdin expecting additional whitespace chars due to the format string he used? There is no need to flush stdout in this scenario. – Carey Gregory Sep 20 '13 at 01:08
2

The answer to your question is in the description of the format specifier (the Whitespace section): http://www.cplusplus.com/reference/cstdio/scanf/

the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).

Zac Howland
  • 15,777
  • 1
  • 26
  • 42