This is a common issue when running C++ programs, especially on Windows. When we run our program, it executes all our instructions very quickly, then immediately exits - often before we can see the output!
There are several ways to handle this. Let's look at the most common approaches:
One way is to use system-specific commands to pause the program:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!\n";
// works on Windows but not recommended
system("pause");
}
Hello World!
Press any key to continue . . .
However, this approach isn't recommended because:
A better approach is to wait for user input:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!\n";
cout << "Press Enter to continue...";
cin.get(); // waits for Enter key
}
Hello World!
Press Enter to continue...
The best solution is to run your program from a command prompt/terminal. The window will stay open until you close it:
For example, if your program is called "hello.exe":
cd C:\MyPrograms
hello.exe
Most IDEs provide ways to keep the console window open:
As you progress in programming, you'll want to get comfortable with running programs from the command line - it's a valuable skill that gives you more control over how your programs run and how you can interact with them.
Answers to questions are automatically generated and may not have been reviewed.
Getting our computer set up so we can create and build C++ programs. Then, creating our very first application