How to Pause a Program in C++?

Pausing programs in C ++ is an important common task with many possible causes like debugging, waiting for user input, and providing short delays between multiple operations. In this article, we will learn how to pause a program in C++.

Pause Console in a C++ Program

We can use the std::cin::get() method to pause the program’s execution until the user provides the input. This function works by extracting a single character from the input stream, effectively causing the program to wait until the next keystroke is pressed and then the program continues with its normal execution.

Syntax to Use std::get Function

cin.get();

C++ Program to Pause a Program Execution in C++

The below program demonstrates how we can pause a program until the user provides input in C++.

C++
// C++ program to pause a program execution

#include <chrono>
#include <iostream>
#include <thread>
using namespace std;

int main()
{
    // Declare an integer variable to hold user input.
    int flag;

    // Print message to inform the user that the program is
    // paused.
    cout << "Your Program is paused! To continue, Press "
            "Enter."
         << endl;

    // Wait for user input.
    flag = cin.get();

    // Print message indicating the program is continuing
    // and will wait for a while.
    cout << "Continuing... Wait for a While" << endl;

    // Pause the program execution for 1000 milliseconds (1
    // second).
    this_thread::sleep_for(chrono::milliseconds(1000));

    // Print message indicating the program has resumed
    // after user input.
    cout << "Program resumed after user input." << endl;

    // Return EXIT_SUCCESS to indicate successful execution
    // of the program.
    return EXIT_SUCCESS;
}


Output

Your Program is paused! To continue, Press Enter.

Continuing...Wait for a While
Program resumed after user input.

Time Complexity: O(1)
Auxilliary Space: O(1)


Contact Us