Hello, I'm learning to start to program in C++, and I have a problem with the prompt closing before the program ends. I know there's a lot of info about it, and I've googled it and searched here, but all the solutions to system("pause") don't work for me.

I'm using Dev-C++, and this is an example of a program that I tried to compile, but it closed after I input the random number.

#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {
		int magic; //Magic number
		int guess; //User's guess
		
		magic = rand(); //Random number function
		
		cout << "Enter your guess: ";
		cin >> guess;
		
		if (guess == magic) { //if guess is right
			cout << "**Right**";
		}
		else {
			cout << "...Sorry, you're wrong.\n";
			cout << "The number was " << magic;
                }

                return 0;
}

I know it's basic, but whatever thing that I try (cin.get(), etc...), it just doesn't seem to work.

Thanks in advance

Recommended Answers

All 9 Replies

So putting cin>>somevariable; before the return 0; doesn't work?

>>but it closed after I input the random number.

Because you programmed it to do that. As ^^^ said you have to put something before the return statement to make the program stop and wait for you to enter something from the keyboard.

Is this what you mean?

#include <iostream>
#include <stdlib.h>
using namespace std;

int main() {
		int magic; //Magic number
		int guess; //User's guess
                int end;
		
		magic = rand(); //Random number function
		
		cout << "Enter your guess: ";
		cin >> guess;
		
		if (guess == magic) { //if guess is right
			cout << "**Right**";
		}
		else {
			cout << "...Sorry, you're wrong.\n";
			cout << "The number was " << magic << "\n";
                }

                cin >> end;

                return 0;
}

It works although I have to do an input, but isn't there another way to do it?

depends: how do you want your program to end?

I was hoping that there could you could just press any key or enter to end it.

You just have to put the following instructions before return 0; :

cin.ignore();
cin.get();

It doesnt close when i run it, i get..

$ CC test.cpp -o main
$ ./main
Enter your guess: 23
...Sorry, you're wrong.
The number was 16838
$


I think it might be your compiler which it closing the file, otherwise it works fine

It doesnt close when i run it

I think he's using Windows (not Linux or Unix or ...)
And in Windows you can just double click on the executable file and it launches, but in his case it will just appear and dissappear directly, if he started it from a console window (what you're doing) it isn't dissappearing ...

So it isn't compiler related ...

I tried your suggestion:

cin.ignore();
cin.get();

return 0;

It worked, and thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.