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


当前回答

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

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

其他回答

简单的

#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()的右大括号上加一个断点。当程序以任何方式结束时,断点将出现,您可以ALT-Tab到控制台窗口以查看输出。

这似乎很有效:

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

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

在任何exit()函数之前或main()中的任何return之前添加以下行:

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");

好吧,我猜你在Windows上使用Visual Studio…为什么?因为如果你在某种Linux操作系统上,那么你可能会从控制台运行它。

不管怎样,你可以像其他人建议的那样在程序的末尾添加一些无用的东西,或者你可以只按CTRL + F5(不用调试就开始),Visual Studio在完成后就会离开控制台。

如果你想运行调试版本而不给你的代码添加垃圾,另一个选择是打开控制台窗口(开始->运行-> cmd)并导航到调试输出目录。然后,只需输入可执行文件的名称,它就会在控制台中运行调试程序。然后你可以使用Visual Studio的attach to process或者其他你想要的东西。