System Pause C++ Command Guide

Are you looking for using System Pause in C++? In this article, I will show you how you can use the system(“pause”) command in C++ to pause the execution of your program.

Before you learn about the system(“pause”), let us discuss the system() function to understand how it works.

What is system() in C++?

system() is the function or method present in stdlib.h and cstdlib.h that is used to invoke an operating system[1] command from a C++ program.

Syntax:

int system(const char *command);

We can use system() to run any command that can run on a terminal if the operating system allows it. On Windows, for example, we can use a system(“dir”) and on a Linux system(“ls”) to list the contents of a directory.

Simple Program using System Pause in C++

Let us take a simple C++ program to understand how can we use the system(“pause”). As in the below program, we are going to an array of numbers from 1 to 10 using for loop.

// C++ program that pauses the Window once value of i reaches 5.
#include <iostream>
using namespace std;
int main ()
{
    for(int i=0;i<10;i++){
      cout<<"value of i is "<<i<<endl;
      if(i==5)
        system("pause")
      }
    system("pause");
    return 0;
}

Output:

System Pause C++ Command Guide

Disadvatages of System Pause Usage in C++

This application is OS-dependent and employs a series of complex processes.

It pauses your software while calling the operating system to launch the operating system shell. The operating system detects the pause and allocates the necessary memory to carry out the task. The software then deallocates memory, exits the Operating System, and resumes the program.

Hence instead of using the system(“pause”), you can use another command such as cin.get(). Note that this command will only work in C++. Since this is defined natively in C++ and is easy to use.

Using cin.get() instead of system(“pause”)

Let us see the example c++ code for system pause in c++. It is mostly advisable to use the natively developed function by c++ than the system commands.

// C++ program that pauses the Window once value of i reaches 5.
#include <iostream>
using namespace std;
int main ()
{
    for(int i=0;i<10;i++){
      cout<<"value of i is "<<i<<endl;
      if(i==5)
        cin.get()
      }
    system("pause");
    return 0;
}

Output:

System Pause C++ Command Guide

As a result, we can observe that both system(“pause”) and cin.get() are waiting for a key to be hit, but cin.get() is not OS dependant and does not follow the procedures to pause the application indicated above.

If you liked our post related to system pause in c++ then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Share your love

2 Comments

Leave a Reply