在 C++ 中使用 system("pause") 命令

在本文中,我们将看看C++中的使用系统(停止)命令。

在浏览本文之前,请注意系统(停止)命令仅在 Windows 系统中可用。

这意味着你不能从任何Linux / Mac机器上使用它。


系统(命令)

在通过系统(停止)命令之前,让我们了解系统()是怎么回事。

1#include <cstdlib>
2
3int system(const char *command);

系统()函数执行呼叫到操作系统执行特定的命令。

请注意,我们必须包含<cstdlib>标题文件。

这类似于打开终端并手动执行该命令。

例如,如果你想使用Linux的ls命令,你可以使用system(ls)

如果你有任何 Linux/Mac 机器,你可以尝试下面的代码。

 1#include <iostream>
 2#include <cstdlib>
 3
 4using namespace std;
 5
 6int main() {
 7    // Try the "ls -l" command from your Linux / Mac machine
 8    int ret = system("ls -l > test.txt");
 9    return 0;
10}
  • 可能的输出*
1total 16
2-rwxr-xr-x 1 2001 2000 9712 Jun 25 21:11 a.out
3-rw-rw-rw- 1 2001 2000 209 Jun 25 21:11 main.cpp
4-rw-r--r-- 1 2001 2000 0 Jun 25 21:11 test.txt

现在我们对system()能做些什么已经很清楚了,让我们来看看系统(pause)命令。


使用C++中的系统命令(停止)

这是一个特定于 Windows 的命令,该命令指示操作系统运行休息程序。

此程序等待终止,并停止对母 C++ 程序的执行,只有在停止程序结束后,原始程序才会继续。

如果您使用的是 Windows 机器,您可以运行以下代码:

 1#include <iostream>
 2#include <cstdlib>
 3
 4using namespace std;
 5
 6int main() {
 7    for (int i=0; i<10; i++) {
 8        cout << "i = " << i << endl;
 9        if (i == 5) {
10            // Call the pause command
11            cout << "Calling the pause command\n";
12            system("pause");
13            cout << "pause program terminated. Resuming...\n";
14        }
15    }
16    return 0;
17}

** 输出 - 从 Windows 系统**

 1i = 0
 2i = 1
 3i = 2
 4i = 3
 5i = 4
 6i = 5
 7Calling the pause command
 8Press any key to continue . . .
 9pause program terminated. Resuming...
10i = 6
11i = 7
12i = 8
13i = 9
14
15E:\Programs\sample.exe (process 14052) exited with code 0.

正如你可以观察到的,当我们的 if 条件 i = 5 时,暂停命令确实执行了。

在我们打进后,我们终止了暂停计划,并恢复了我们在C++中的( / 社区 / 教程 / 环节-in-c-plus-plus)计划!

使用系统(休息)命令的缺点

系统的主要陷阱(暂停)是它是平台特定的,它不适用于Linux/Mac系统,也不可携带。

虽然这对Windows系统来说是一种黑客攻击,但当你试图在其他系统上运行代码时,这种方法很容易导致错误!

因此,我会建议一些其他方法来暂停和恢复程序,例如使用信号处理器。


结论

在这篇文章中,我们了解了如何在C++中使用系统(停止)命令. 对于类似的内容,请参阅我们关于C++编程的教程(/community/tutorials/c-plus-plus)!

参考


Published At
Categories with 技术
Tagged with
comments powered by Disqus