cin.get extracts a single character from the stream and returns it, cin.ignore extracts characters up the the number specified or the character specified is reached and discards them.
I'm writing a very simple program that asks you to enter a number and it prints it back to you. Today I just learned the correct way to pause a program so I'm practicing using it. Well heres the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <limits>
usingnamespace std;
int main()
{
cout << "Enter a number ";
int x;
cin >> x;
cout << x << endl;
//Pause
cout << "Press ENTER to quit";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
The problem is that when I enter a number and press enter the program closes right away and it doesn't even pause. How can I fix this?
Hm, I would have expected that to pause it. It seems that something is remaining in the string, so when you tell it to ignore or get it's using what's in the stream and not asking for a new one. If that's the case, you should put cin.sync(); before cin.ignore to clear it
Edit: I did a test and saw that it was leaving the new line character in the stream. I new it was good to always clear the stream before using cin in case anything was left, but I didn't realize it left the new lines.
cin.clear sets the error state flag to goodbit meaning no errors (by default, you can pass it different flags). If you're going to use cin and you aren't sure of what state it's in, it's good to both clear and sync it.
cin.ignore(streamsize n, int delim) means ignore up to and n characters or the character delim is found. numeric_limits<streamsize>::max() is the maximum size of the stream, so in that case it will ignore up to '\n' which is a new line