I am soon to post an article on this... it is pretty big since the subject is fairly in-depth... but the simple answer is just
You can't and/or shouldn't fflush() stdin.
Remember,
fflush() is
not defined on input streams! It does not matter that it always worked for
you in the past -- it is non-standard and
will break at some point.
What typically is asked is simply to get rid of pending input before the end of the line. For that, simply use one of:
1 2 3 4 5 6
|
// C++
#include <iostream>
#include <limits>
using namespace std;
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
|
1 2 3 4 5
|
/* C */
#include <stdio.h>
int c;
do c = getch(); while ((c != EOF) && (c != '\n'));
|
Completely clearing the user input is a different matter, and is typically not recommended except in special circumstances (which I will endeavor to touch upon in my upcoming article), since it requires special conditions and programming.
Unfortunately, the
istream::
sync() method, I've learned, isn't very clearly defined and has little use.
I just married so it may be a week before I can post the article. In lieu of seeking to do things like flush the input, I heartily recommend you use
getline() and
stringstreams as
Bazzy suggests. The user always expects to press
ENTER after every input, so your input routines should match -- read a line of input, then parse it properly. Don't use formatted input methods directly from the user.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string name;
unsigned age;
cout << "What is your name? " << flush;
getline( cin, name );
cout << "How old are you? " << flush;
{
string s;
getline( cin, s );
if (!(istringstream( s ) >> age)) //yoinks! fixed this
age = 0;
}
cout << "Hello, " << name << "!\nYou are " << age << " years old.\n";
return 0;
}
|
Hope this helps.