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


当前回答

对于Visual Studio(并且只有Visual Studio),下面的代码片段给了你一个'wait For keypress to continue'提示,它真正地等待用户显式地按下一个新键,首先刷新输入缓冲区:

#include <cstdio>
#include <tchar.h>
#include <conio.h>

_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();

注意,这里使用了tchar.h宏来兼容多个“字符集”(vc++称之为字符集)。

其他回答

和你的答案相似,只是极简主义的选择。

创建一个包含以下内容的批处理文件:

helloworld.exe
pause

然后使用批处理文件。

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

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

简单的

#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上使用Visual Studio…为什么?因为如果你在某种Linux操作系统上,那么你可能会从控制台运行它。

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

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

这里有个问题,不太明显。不知怎么的,我在程序的最后一行添加了一个调试断点。不知道我是怎么做到的,可能是在不同屏幕之间跳跃时错误地点击了鼠标。我在VS Code工作。

当我进行调试时,系统立即跳转到那个断点。没有错误消息,没有临时输出,什么都没有。我就想,程序是怎么通过我设置的所有断点的?我花了太长时间才想明白。

显然,系统将最后一行断点视为“第一个”停止。简单的解决方法?删除断点,哎呀!(此处插入前额。)