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

其他回答

如果您实际上是在Visual c++中调试应用程序,请按F5或工具栏上的绿色三角形。如果你不是真的调试它(你没有设置断点),按Ctrl+F5或选择菜单上的Start Without debugging(它通常在Debug菜单上,我同意这是令人困惑的)。它会更快一点,更重要的是,它会在结束时暂停,而无需更改代码。

或者,打开命令提示符,导航到exe所在的文件夹,并通过键入它的名称来运行它。这样,当它完成运行时,命令提示符不会关闭,并且您可以看到输出。我更喜欢这两种方法,而不是添加代码,在应用程序完成时停止它。

包括conio.h,在代码的末尾,在返回0之前,写入_getch();

这似乎很有效:

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

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

我通常只在main()的右大括号上加一个断点。当程序以任何方式结束时,断点将出现,您可以ALT-Tab到控制台窗口以查看输出。

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

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