Inside Man
Inside Man

Reputation: 4319

Cin.Ignore() is not working

Here I have a code:

cout << "Press Enter To Exit...";
cin.ignore();

this program will execute and will wait till you press enter and then it will exit. now see this code:

int m;
cin >> m;
cout << "Press Enter To Exit...";
cin.ignore();

this time after entering a number for saving in "m" the program will exit without waiting for cin.ignore command which waits for pressing enter.

I mean if you use cin command before cin.ignore, the cin.ignore command will skip. why? and what should I do for fixing it?

Upvotes: 1

Views: 14160

Answers (4)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 413

cin.ignore() basically clears any input left in memory. In the first piece of code, you did not input anything, hence it will have nothing to clear and because of that it waits for you to input something. In the second piece of code you used the >> operator which gets formated input but leaves the end line character '\n' (the one that gets stored when you press ENTER) wandering in the input buffer. When you call cin.ignore() it then does it job and clears that same buffer.As it already did what he was called to it simply lets the program continue (in this case to the end). Remember cin.ignore() is for clearing the input buffer(small piece of memory that holds the input) if you want the user to input something before the program moves on use cin.get().

You should also know this:

If using:

->cin<< you should call cin.ignore() afterwards because it does not consume the end line character '\n' which will be consumed next time you ask for input causing unwanted results such as the program not waiting for you to input anything.

->cin.get() you should not call cin.ignore() because it consumes the '\n'

->getline(cin,yourstring) (gets a whole input line including the end line character) you should also not use cin.ignore()

Upvotes: 5

Deepak
Deepak

Reputation: 480

when you use cin >> m you type value of m and then press enter, the enter '\n' goes into buffer and cin.ignore(); ignores it and program ends.

Upvotes: 1

Aman Aggarwal
Aman Aggarwal

Reputation: 4015

Use

int m;
cin >> m;
cin.ignore();

cout << "Press Enter To Exit...";
cin.ignore();

Upvotes: 2

NFRCR
NFRCR

Reputation: 5580

Use this.

std::cin.sync(); std::cin.get();

Upvotes: 1

Related Questions