最近,我一直试图从这个网站学习c++。不幸的是,每当我试图运行其中一个代码示例时,我看到该程序打开了大约半秒钟,然后立即关闭。有没有办法阻止程序立即关闭,以便我能看到我的努力的成果?


当前回答

简单的

#include <cstdio>

    int main(){
        // code...
        std::getchar();
        std::getchar();
        return 0;
    }

for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately. so what we aim to is a simple way of preventing a program from finishing after it outputs everything. Of course there are more complex and clean ways to solve this, but this is the simplest.

其他回答

如果你正在运行Windows,那么你可以执行system("pause >nul");或系统(“暂停”);。它执行一个控制台命令来暂停程序,直到您按下一个键。>nul阻止它说按任意键继续....

调用cin.get ();2次:

    //...
    cin.get();
    cin.get();
    return 0
}

如果你使用的是Windows,为什么不直接从控制台运行这个程序呢?这样,程序结束后窗口仍保持打开状态。

[编辑]:当我使用KDevelop4时,IDE底部的一个选项卡中运行着一个完整的Bash实例(一个Linux CLI)。这就是我在这种情况下使用的方法。

简单地把它放在代码的末尾:

而(1){}

这个函数将一直运行下去(或者直到您关闭控制台为止),并将防止控制台自己关闭。

James的解决方案适用于所有平台。

或者在Windows上,你也可以在从main函数返回之前添加以下内容:

  system("pause");

这将运行暂停命令,等待直到你按下一个键,并显示一个漂亮的消息按任意键继续…