在C++中使用system(" pause")命令
时间:2020-02-23 14:30:07 来源:igfitidea点击:
在本文中,我们将介绍如何在C++中使用system(" pause")命令。
在阅读本文之前,请注意,只有在Windows系统中才可以使用system(" pause")命令。
这意味着您不能在任何Linux/Mac计算机上使用它。
system()命令
在执行system(" pause")命令之前,让我们了解一下system()的作用。
#include <cstdlib> int system(const char *command);
system()函数执行对操作系统的调用以运行特定命令。
注意,我们必须包含 <cstdlib>头文件。
这非常类似于打开终端并手动执行该命令。
例如,如果要在Linux中使用" ls"命令,则可以使用" system(" ls")"。
如果您有任何Linux/Mac计算机,则可以尝试以下代码。
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
//Try the "ls -l" command from your Linux/Mac machine
int ret = system("ls -l > test.txt");
return 0;
}
可能的输出
total 16 -rwxr-xr-x 1 2001 2000 9712 Jun 25 21:11 a.out -rw-rw-rw- 1 2001 2000 209 Jun 25 21:11 main.cpp -rw-r--r-- 1 2001 2000 0 Jun 25 21:11 test.txt
现在我们对" system()"可以做什么有一个清晰的认识,让我们看一下system(" pause")命令。
在C++中使用system(" pause")命令
这是Windows特有的命令,它告诉OS运行" pause"程序。
该程序等待终止,并停止执行父C++程序。
仅在暂停程序终止后,原始程序才会继续。
如果您使用的是Windows计算机,则可以运行以下代码:
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
for (int i=0; i<10; i++) {
cout << "i = " << i << endl;
if (i == 5) {
//Call the pause command
cout << "Calling the pause command\n";
system("pause");
cout << "pause program terminated. Resuming...\n";
}
}
return 0;
}
输出–从Windows系统
i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 Calling the pause command Press any key to continue . . . pause program terminated. Resuming... i = 6 i = 7 i = 8 i = 9 E:\Programs\sample.exe (process 14052) exited with code 0.
如您所见,当if条件i = 5时,确实执行了stop命令。
按下回车键后,我们终止了暂停程序,并在C++程序中恢复了循环!
使用system(" pause")命令的缺点
系统的主要缺陷("暂停")是特定于平台的。
这在Linux/Mac系统上不起作用,并且不可移植。
尽管这对于Windows系统来说是一种hack,但是当您尝试在其他系统上运行代码时,这种方法很容易导致错误!
因此,我建议使用其他替代方法来暂停和恢复程序,例如使用信号处理程序。

