Console closing, seemingly ignoring cin.get()

Hello,
On line 14, I expected the console to stay open long enough for the user to press a key while displaing some text. When I run this (using Visual Studio Express 2010), it simply closes the console upon inputting "53".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main()
{
	int n = 1;
	int guess, answer = 53;

	cout << "Guess the number (1-100):";
	do {
		cin >> guess;
		if (guess == answer) {
			cout << guess << " is the correct answer!";
			cin.get();
			n = 0;
		}
		else 
			cout << "Guess again:";
	} while (n != 0);
	return (0);
}

I noticed that if I duplicate line 14, then the console awaits input, then closes. What would be the correct way to keep the console open (without using system("Pause"))?
Last edited on
What would be the correct way to keep the console open
executing the program from the console. (after all it is a console program)

The program exits immediately because a '\n' remains in the buffer and that is what cin.get() reads.
Ah. I think I get it now. Though it's true that it is a console program, the intention I want is for the executable to be run outside of the console (via windows explorer or other).

So would be it logical that I clear the buffer prior to line 14?
http://www.cplusplus.com/forum/articles/7312/
You better do it just before the return. However I'm not sure of how, maybe
1
2
cin.ignore( numeric_limits<streamsize>::max(), '\n');
cin.get();


You could also make a wrapper program that will remain open even in case of fatal errors or exceptions. http://www.cplusplus.com/forum/beginner/1988/3/#msg14102 (windows)

By the way, break will break from a loop, so you don't need that dummy variable.
What's wrong with this?
1
2
cin.sync();
cin.ignore();
This way you just press enter, and you don't have to type out long code.
Here it is mate... :))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main()
{
	int n = 1;
	int guess, answer = 53;

	cout << "Guess the number (1-100):";
	do {
		cin >> guess;
		if (guess == answer) {
			cout << guess << " is the correct answer!";
			
			n = 0;
		}
		else 
			cout << "Guess again:";
	} while (n != 0);

	
	cin.get(); cin.get();
	return 0;
}
Ok guys, appreciate all the feedback and ideas! I think I see what to do now. What a nice forum :)
Just to throw in my two cents. Whatever you decide to use, make it into a function. The first thing I type into any new project I start these days is this:
1
2
3
4
5
void pause()
{
     std::cin.sync();
     std::cin.ignore();
}


This way no matter where I want to pause the programs execution I just have to enter pause(); and it's done.
Last edited on
Topic archived. No new replies allowed.