cin.ignore cin.get

Hello people,

Can you guys please tell me what the difference is between cin.get and cin.ignore and when I should use them.

Thanks ahead of time :D
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>
using namespace 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.
Last edited on
Yes, it worked. But can you tell me what cin.sync() does.
it clears the stream of any remaining input.
Oh ok but I though cin.clear does that.
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.
Last edited on
Oh ok. Also, what do the parameters mean in cin.ignore().
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
Ok so if i said cin.ignore(100, 8) it will ignore 100 numbers and characters or up to the number 8 but not including 8?
if you want it to ignore the character 8, you have to put it as '8', otherwise it would ignore what is 8 on the ascii chart
Ok I get it. Thanks for all the help :D
Topic archived. No new replies allowed.