cin.ignore() question

Why does cin.ignore() not keep the console open in the following program??
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main(){
	char b[100];
	int d;
	cin>>b;
	cin>>d;
	cin.ignore();
	return 0;
}


if I place cin.ignore(INT_MAX, '\n'); before cin.ignore(); then the program will pause until I press enter. Why is this?
std::cin.ignore() gets one character and discards it if there is one to get. In this case, the character in question is the '\n' left over from cin >> d;. Since it successfully discarded a character, it doesn't need to pause.

Happy coding!

-Albatross
Last edited on
Oh, I see. So What happens to the '\n' after cin >>b;?
It gets eaten by the cin>>d, because the operator >> for integers ignores leading whitespace (which includes '\n' characters).
At the risk of being flamed, I suggest just using system("pause") to keep your program open until you press a key. There's a huge debate about whether this is the "right" way to do it, but if you're just coding a small program to learn C++ (which is what it seems) then this is the easiest route in my opinion.
I agree, it's not so bad for simple/test/etc, applications.

Alternately, use Code::Blocks, and it leaves the console open on exit anyway. I don't understand why VS doesn't support that TT
Last edited on
Hello I am a UAT student and I am taking a C++ class. I couldn't help but read this forum about cin.ignore(). Well if your just keeping it system("pause") does work but i've heard there is some trouble with that. If you want to go with that do so but if not you could always but cin.get() instead of ignore(). Get() waits basically untill you press a key same as pause so which ever one works. Here is the code if you are confused where to put cin.get().

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main(){
	char b[100];
	int d;
	cin>>b;
	cin>>d;
	cin.get();
	return 0;
}
 


I hope this helps. =]
Get() waits basically untill you press a key same as pause so which ever one works.

Er... really?

http://cplusplus.com/reference/iostream/istream/get/
int get();
Extracts a character from the stream and returns its value (casted to an integer).


-Albatross
Last edited on
Topic archived. No new replies allowed.