Proper Use of cin.ignore()?

I have seen a few code samples of cin.ignore() being used, but I am still not totally clear about all the situations in which it should be used.

Should it be used before accepting input from the console only?
Or also from an input file?
Is it only applicable if a cout statement has been made beforehand?

At the moment, the program I am writing accepts a character input from the console, and the only purpose for doing that is to hold the console open long enough for the user to read instructions or error messages (if something goes wrong). For example,

 cout << "There has been an error in sub-section A. Check data and re-run the program. Enter any key to continue. \n";
 cin >> rflag;

Should I add a cin.ignore() just before the cin statement?

Is there a better way to do this?
cin.ignore() is sometimes used to catch a newline character left in the buffer by cin. Whether or not there is a cout makes no difference.

Another use is for your situation.
Duoas provided a color program example to demonstrate this.
Last edited on

I also read through the thread you linked too. Wow! There is a lot of good information there. But it takes a while to sift through it.

Perhaps it might be worthwhile to extract the useful information from that thread and post a complete example of how to keep the console open on a single tutorial page. Whatever technique was determined to be the best.

That way, somebody doesn't have to wade through 7 pages of
"This might work"
"That doesn't work"
"This is a better way"
"Did you read the rest of the thread?"
"My way works"
"No, it doesn't"
"Your way sucks"
"I am a new user with a question completely off topic"

All I want is to get to the point. A one-page tutorial showing current best practice for keeping a console open, with and without errors, would be wonderful.
I had the same idea and I brought it up in a Lounge thread once, but I think I got ignored.
Topic archived. No new replies allowed.