printf and scanf command

This is a discussion on printf and scanf command within the C++ Programming forums, part of the General Programming Boards category; I was wondering if anyone could tell me why the second scanf is skipped after i enter one number and ...

printf and scanf command

I was wondering if anyone could tell me why the second scanf is skipped after i enter one number and then hit enter? I am trying read two values from the keyboard and send them through a pipeline. Does anyone know which function to call for the program to store the keyboard character that is pressed to a char variable right after the key has been pressed without a following enter (line carriage)? Thanks!

It's because scanf()'s &#37;c matches newlines as well as ordinary characters. When you tell scanf to read a number and enter "123\n", it takes the "123" and leaves the "\n" for the next scanf to read when looking for a character.

There are lots of ways around this problem. The best is probably to read input as lines with fgets() and then use sscanf() to parse those lines.

"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell

Note that this is C, not C++. And of course, the second scanf isn't skipped -- there's a perfectly good character waiting to be input, namely the enter key from the first time. You can do another scanf, if you like, or to actually do it in a reasonable way, do scanf("%d"), since scanf skips whitespace when looking for numbers. (Of course, temp would then need to be an int and not a char.)