Reputation: 83
Is fflush(stdin) is really required in C++ and is it good to do it this way to flush the newline in the buffer?
Upvotes: 2
Views: 6168
Reputation: 47418
The call to fflush(stdin)
is undefined behavior in C (and, consequetly, in C++).
The C language standard, ISO 9899:1999 states in 7.19.5.2/2
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined
To discard the entire input up to the next end of line, in C++, the most robust approach is
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
As for the program "flashing and going away", are you perhaps executing a console application on a Windows platform? Such applications are best executed from a console window (Start->run->cmd.exe)
Upvotes: 9
Reputation:
Use cin.get ()
instead of getchar ()
and you should be fine. The problem is that C++ I/O streams and C I/O functions are working on top of the same file descriptors, but have different buffers. I can't tell what exactly is going on w/o debugging, but it feels like getchar()
that you are calling to pause a program until character is entered is getting characters that were already read by C++ input stream. So it gets data and unblocks, so you exit the program.
If you still have the problem, make sure you don't enter `\n' characters (i.e. don't press enter). Because pressing enter after input is actually a character that you can read. This problem is usually solved with peeking (see http://www.cplusplus.com/reference/iostream/istream/peek/).
Upvotes: 4
Reputation: 15099
The getchar()
at the end of your code gets the next character in stdin (input buffer). If there is no character there, then it will wait until the user enters something. fflush(stdin) clears the input buffer.
This is why your code will wait if you have the fflush, because you are clearing the input buffer, causing getchar to wait for the user's next input. However it looks like you are leaving something on the buffer, causing getchar to 'get' it, which ends your program.
If you'd like the program to stay open after you're done, then leave the flush there. If you'd like it to close right away, then remove the flush.
Upvotes: 0