How to stop C++ console application from exiting immediately?


Sometimes we have noticed that the console is being closed immediately after displaying the result. So we cannot see the result properly. Here we will see how we can stop the console from closing.

The idea is very simple. We can use the getchar() function at the end. This will wait for one character. If one character is pressed, the console will exit.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   cout << "Hello World" << endl;
   getchar();
}

Output

Hello World
5

Here button 5 was pressed when it is waiting for a character.

Updated on: 30-Jul-2019

710 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements