简体   繁体   中英

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?

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()

Use

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

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

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.

用这个。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM