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


当前回答

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

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

helloworld.exe
pause

然后使用批处理文件。

其他回答

如果你正在使用微软的Visual c++ 2010 Express,并遇到CTRL+F5无法在程序终止后保持控制台打开的问题,请查看这个MSDN线程。

可能你的IDE被设置在CTRL+F5运行后关闭控制台;事实上,Visual c++ 2010中的“空项目”默认关闭控制台。要改变这一点,请按照微软版主的建议执行:

请右键单击您的项目名称,进入属性页面,展开配置属性->连接器->系统,在子系统下拉菜单中选择控制台(/子系统:控制台)。因为,在默认情况下,Empty项目不指定它。

简单的

#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.

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

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

这似乎很有效:

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

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

编辑:正如Charles Bailey在下面的评论中正确指出的那样,如果stdin中缓冲了字符,这将不起作用,而且真的没有好方法来解决这个问题。如果运行时附带调试器,John Dibling建议的解决方案可能是解决问题的最干净的解决方案。

也就是说,我把它留在这里,也许其他人会觉得它有用。在开发期间编写测试时,我经常使用它作为一种快速的方法。


在main函数的末尾,你可以调用std::getchar();

这将从stdin中获取单个字符,从而为您提供“按任意键继续”类型的行为(如果您确实想要“按任意键”消息,则必须自己打印一条)。

你需要为getchar添加#include <cstdio>。