Tuesday, January 19, 2010

Clear input stream in C++ - fflush(stdin) equivalent in C

You can't use flush to clear the input stream in C++, it's equivilent to using fflush(stdin) for C. Sometimes it works, sometimes it doesn't, but all of the time it's a bad idea.

cin >> flush;

To clear the input stream in C++ use cin.ignore() everytime you think the input stream may still have data in it.

cout<<"Enter your name"<cin.getline(name, 50, '\n'); //ignore not needed, getline does it
cout<<"Enter your age"<cin>>age; cin.ignore(); //clear the newline from the stream
cout>>"Enter your height"<cin>>height; //this will work now

No comments: