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

>>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?

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

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.

This question has already been answered. Start a new discussion instead.