【问题标题】:system() function not working C++system() 函数不工作 C++
【发布时间】:2014-01-14 02:42:55
【问题描述】:

我目前正在关注由 thenewboston 在 youtube 上创建的教程。我没有逐字逐句地遵循它,但已经足够接近了。

我的简单程序:

#include <iostream>
#include <string.h> /* memset */
#include <unistd.h> /* close */
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>

int main(){
    using namespace std;
    cout << "Those who wander too far off the path of reality. Will be plunged into total Madness." << endl;
    cout << "                                                                                          - BinKill-Ethical" << endl;
    system("cls");
    return 0;

}

这是我创建的第一个 C++ 程序。我几乎一无所知,但我无法让 system() 函数工作。

输出:

除了#include &lt;iostream&gt; 之外的所有内容都是来自其他 stackoverflow 帖子的建议,以尝试使其正常工作。没有一个工作。如果这很重要,我正在使用 G++ 进行编译。

【问题讨论】:

  • 就 C++ 而言,system 不能保证任何结果。你没有cls 命令(Windows 默认有,这就是教程使用的)。
  • 使用system("cmd /c cls");
  • @CaptainObvlious,不是 Windows,由 &lt;unistd.h&gt; 判断。
  • 既然你有输出“cls: not found”,这意味着你的system()函数正在工作!
  • 但是“CLS”不是。

标签: c++ system


【解决方案1】:

如果您使用的是 Linux,则可以改用以下内容:

system("clear");

假设你想在打印前清屏,你的代码变成这样:

#include <iostream>
#include <string.h> /* memset */
#include <unistd.h> /* close */
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>

int main(){
    using namespace std;
    system("clear");
    cout << "Those who wander too far off the path of reality. Will be plunged into total Madness." << endl;
    cout << "                                                                                          - BinKill-Ethical" << endl;
    return 0;

}

【讨论】:

    【解决方案2】:

    system 函数用于启动目标平台上存在的可执行文件。在 Windows 平台上,cls 命令内置在 shell 中,不作为独立的可执行文件存在。这使得仅使用system("cls") 无法清除屏幕,因为名为“cls”的可执行文件不是 Windows 的标准部分。您仍然可以在默认安装的 Windows 上清除屏幕,但您必须通过启动命令 shell 来完成。

    system("cmd /c cls");
    

    /c 选项指示 shell (cmd) 执行命令 cls 然后退出。

    如果您是专门为 Windows 编写程序,我建议您查看console API。如果您正在为多个平台编写应用程序,我建议您查看ncurses。两者都可以让您以更加程序化的方式清除屏幕,而不仅仅是使用system

    【讨论】:

    • 呃,这不正确。 system() 启动一个 shell,而不仅仅是任何可执行文件。因此system("cls") 可以正常工作(并且在 Windows 系统上总是如此)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2012-07-18
    • 2016-05-16
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    相关资源
    最近更新 更多