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

其他回答

我使用cin.get(),这是有效的,但有一天我需要使用另一个cin。get([数组变量])之前获取一个中间有空白字符的ling字符串。因此,cin.get()并没有避免命令提示符窗口关闭。最后我找到了另一种方法: 按CTRL+F5在外部窗口中打开,Visual Studio不再对其进行控制。只会在最后的命令运行后询问关闭。

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

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

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

你所要做的就是为x设置一个变量,然后在返回0之前输入这个;

cout<<"\nPress any key and hit enter to end...";
cin>>x;

以调试模式启动,使用F5运行代码 要停止你的控制台应用程序,不要点击红叉,而是按CTRL-break 你会在程序的最后碰到所有的断点。

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