system PAUSE
Наверняка где-то в примерах программ на С++ вы встречали что-то типа этого:
Обычно мало кто задумывается, что здесь делает и зачем строка system(«PAUSE»); . А я вот задумался ))) И решил, что это может быть любопытно не только мне, поэтому расскажу об этом подробно(есть ещё видео в конце статьи).
Итак, стандартная функция system() вызывает командный интерпретатор (это cmd.exe или command.com ). Синтаксис функции:
int system(const char* command);
Функция возвращает определённое реализацией языка значение (обычно это то, что возвращает вызванная программа).
Если в качестве параметра передаётся нулевой указатель, то функция проверяет наличие в системе командного интерпретатора. Если его нет (или не найден), то будет возвращён 0, а есть он есть, то возвращаемое значение будет не нулевым.
Так что вызов функции с параметром «PAUSE» выполнит следующие действия:
- Запустит командный интерпретатор
- Выполнит команду PAUSE
То есть выведет сообщение “Для продолжения нажмите любую клавишу…” и приостановит выполнение программы до тех пор, пока пользователь не нажмёт клавишу.
Разумеется, таким образом можно выполнять не только команду PAUSE . Так можно выполнять любые команды, которые поддерживаются интерпретатором. Например, MKDIR — создаёт каталог, DIR — выводит на экран содержимое текущего каталога ну и так далее.
Кроме того, так можно запускать внешние программы. Например:
запустит стандартный калькулятор Windows.
Ну и напоследок ложка дёгтя. Поскольку эта функция вызывает стандартный командный интерпретатор Windows, то она работает только в Windows. Так что если вы пишите программу для другой операционной системы, то воспользоваться этой функцией не получится.
System Pause C++
For running the code, we install DEVC++. To run the codes, tap the button F11 from the keyboard.
Usage of System (“Pause”) Command:
The system (“pause”) command is used to execute the pause code. The code is waiting to finish and will stop running the parent C ++ code. The original code will only continue after the pause code ends. If we use a Windows operating system, we can run the following program.
In this example, we utilize two header files: #include <iostream> and #include <cstdlib>. To utilize the system (“pause”) command in the program, we must include the “#include <cstdlib>” header file at the start of the program.
Before decoding a program into machine language, the compiler carries out the header files. Next, we use the main() function. Here, the “For” loop contains three statements. The variable used inside the loop is “k.” We initialize the variable “k” to 1. Then, we apply the test condition k<8, it tests the loop every time to observe if k is less than 8. If the defined condition is true, the loop body is implemented. If the condition is false, the loop ends and moves on to the next statement. This completes the entire program:
#include <iostream>
#include <cstdlib>
using namespace std ;
int main ( ) {
for ( int k = 1 ; k < 8 ; k ++ ) {
cout << "k = " << k << endl ;
if ( k == 3 ) {
cout << "Call the pause program \n " ;
system ( "pause" ) ;
cout << "the pause program is terminated. Resuming. \n " ;
}
}
return 0 ;
The final statement k++ increments the variable “k” every time the loop is implemented. Even when the “for” loop ends, the variable “k” in the loop is well-defined and has the values assigned in the last increment. Cout is an output function. The double quotation marks surround the message we want to print. The statements in the program end with a semicolon. So, a semicolon is utilized at the end of the cout statement:

As we see, the code is executed, and the first three values of “k” are shown as an output. The system (“pause”) command executes. When we pressed the enter key to continue, it exited the paused code and continued the loop in the code. And by this, we get the next 4 values of k.
Using Cin.get() Function
Cin.get() function is one of the alternatives existing for the system function (“pause”). It will break the execution of the program when needed. After execution, the cin.get() method waits for user input before continuing. As soon as we enter the input, the program will continue to run. This method is helpful if there is a need to enter a value in the code during implementation. This function is a program-level method, and it does not call the operating system to implement the commands. It is a standard library function, so we don’t need to explicitly add a distinct header file. We utilize the cin.get() function as shown below:
#include<iostream>
using namespace std ;
int main ( )
{
int Values [ 10 ] = { 30 , 50 , 70 , 90 , 110 , 120 , 140 , 160 , 180 , 210 } ;
for ( int j = 0 ; j < 10 ; j ++ )
{
if ( Values [ j ] == 160 )
{
cout << "Number 160 is present at array position: " << j ;

First, we add a header file in the program. We apply the main function. We take any 10 random numbers and generate an array of these numbers. The variable used inside the loop is “j”. First, we initialize the variable and then apply the test condition. The variable “j” gives the value until it satisfies the given condition. We want to know the position of the value “160”. We utilize the cout function. The message we want to print is “number 160 is present at array position”. In the end, we utilize the cin.get() function:

As the number 160 is present at the 8th position in the array, we get the output 7 because the index of the array starts with 0. So, the digit present at the 8th index shows the 7th position.
System() Function:
The system() is a predefined usual library function. We pass input commands to the system() function, then these commands will be implemented on the operating system terminal. This function calls the Operating System to execute a specific command. This may be very much like launching a terminal and implementing the command with the aid of using a hand:
#include <iostream>
#include <cstdlib>
using namespace std ;
int main ( )
{
if ( system ( NULL ) )
cout << "Command processor is running" ;
else
cout << "Command processor is not running" ;

It is a common approach to test if we can run instructions using a system() in an Operating System. In this program, we should encompass the header file <cstdlib>. We include the header file <iostream>. These header files are applied at the start of the code. We apply the if-else condition. Inside the condition, we utilize the system() function. When we pass a parameter null pointer to the system() function instead of a string, the system() function returns the statement that the command processor is running. Otherwise, the command processor is not running.

Conclusion:
In the article, we talked about system pause C++. We see the program utilizing the system (“pause”) command. It is used to run the pause commands. If we are not sure to use the system (“pause”), then we use the cin.get() function. It also waits for us to enter any value. We have also discussed the system() function. We hope you found this article helpful. Check out other Linux Hint articles for more tips and tutorials.
About the author

Omar Farooq
Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.
Using the system("pause") command in C++

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
In this article, we’ll take a look at using the system(“pause”) command in C++.
Before going through this article, note this the system("pause") command is only available in Windows Systems.
This means that you cannot use this from any Linux / Mac machine.
The system() command
Before going through the system(“pause”) command, let’s understand what system() does.
The system() function performs a call to the Operating System to run a particular command.
Note that we must include the <cstdlib> header file.
This is very similar to opening a terminal and executing that command by hand.
For example, if you want to use the “ls” command from Linux, you can use system("ls") .
If you are having any Linux/Mac machine, you can try the below code.
Possible Output
Now that we’re a bit clear on what system() can do, let’s look at the system(“pause”) command.
Using system(“pause”) command in C++
This is a Windows-specific command, which tells the OS to run the pause program.
This program waits to be terminated, and halts the exceution of the parent C++ program. Only after the pause program is terminated, will the original program continue.
If you’re using a Windows machine, you can run the below code:
Output — From Windows System
As you can observe, the pause command was indeed executed when our if condition i = 5.
After we hit enter, we terminated the pause program, and resumed our loop in C++ program!
Disadvantages of using the system(“pause”) command
The main pitfall of system(“pause”) is that this is platform specific. This does not work on Linux/Mac systems, and is not portable.
While this works as a kind of a hack for Windows systems, this approach may easily cause errors, when you try to run the code on other systems!
Therefore, I would suggest some other alternative ways to pause and resume a program, such as using signal handlers.
Conclusion
In this article, we learned how we could use the system(“pause”) command in C++. For similar content, do go through our tutorial section on C++ programming!
References
-
page on system() in C++
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
System pause c что это
system() is used to invoke an operating system command from a C/C++ program.
Note: stdlib.h or cstdlib needs to be included to call system.
Using system(), we can execute any command that can run on terminal if operating system allows. For example, we can call system(“dir”) on Windows and system(“ls”) to list contents of a directory.
Writing a C/C++ program that compiles and runs other program?
We can invoke gcc from our program using system(). See below code written for Linux. We can easily change code to run on windows.
system() vs using library functions:
Some common uses of system() in Windows OS are, system(“pause”) which is used to execute pause command and make the screen/terminal wait for a key press, and system(“cls”) which is used to make the screen/terminal clear.
However, making a call to system command should be avoided due to the following reasons:
- It’s a very expensive and resource heavy function call
- It’s not portable: Using system() makes the program very non-portable i.e. this works only on systems that have the pause command at the system level, like DOS or Windows. But not Linux, MAC OSX and most others.
Let us take a simple C++ code to output Hello World using system(“pause”):
The output of the above program in Windows OS:
This program is OS dependent and uses following heavy steps.
- It suspends your program and simultaneously calls the operating system to opens the operating system shell.
- The OS finds the pause and allocate the memory to execute the command.
- It then deallocate the memory, exit the Operating System and resumes the program.
Instead of using the system(“pause”), we can also use the functions that are defined natively in C/C++.
Let us take a simple example to output Hello World with cin.get():
The output of the program is :
Thus, we see that, both system(“pause”) and cin.get() are actually performing a wait for a key to be pressed, but, cin.get() is not OS dependent and neither it follows the above mentioned steps to pause the program.
Similarly, in C language, getchar() can be used to pause the program without printing the message “Press any key to continue…”.
A common way to check if we can run commands using system() in an OS?
If we pass null pointer in place of string for command parameter, system returns nonzero if command processor exists (or system can run). Otherwise returns 0.
Note that the above programs may not work on online compiler as System command is disabled in most of the online compilers including GeeksforGeeks IDE.
This article is contributed by Subhankar Das. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.