最近,我一直试图从这个网站学习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.

其他回答

你甚至可以在main()函数的开头声明一个整数(比如int a;),然后输入std::cin >> a;就在返回值之前。因此,程序将一直运行,直到你按下一个键并进入。

我试着在最后放一个getchar()函数。但这并没有起作用。所以我所做的就是一个接一个地添加两个getchar()函数。我认为第一个getchar()吸收了您在最后一个数据输入后按下的Enter键。所以尝试添加两个getchar()函数而不是一个

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

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

如果您正在使用Visual Studio,并且正在从IDE启动控制台应用程序:

按CTRL-F5(启动而不调试)将启动应用程序并保持控制台窗口打开,直到按下任何键。

这似乎很有效:

cin.clear();
cin.ignore(2);

如果您先清除缓冲区,那么当您读取下一个缓冲区时就不会有问题。 由于某些原因,sin .ignore(1)不起作用,它必须是2。