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

其他回答

简单地把它放在代码的末尾:

而(1){}

这个函数将一直运行下去(或者直到您关闭控制台为止),并将防止控制台自己关闭。

使用#include "stdafx.h" & system("pause");就像下面的代码一样。

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
    std::cout << "hello programmer!\n\nEnter 2 numbers: ";
    int x, y;
    std::cin >> x >> y;
    int w = x*y;
    std::cout <<"\nyour answer is: "<< w << endl;
    system("pause");
}

这似乎很有效:

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

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

查看您的IDE在项目设置中是否有一个复选框,以便在程序终止后保持窗口打开。如果不是,使用std::cin.get();读取主函数末尾的一个字符。但是,请确保只使用基于行的输入(std::getline)或处理剩余的未读字符(std::ignore until newline),否则末尾的.get()将只读取之前未读的垃圾。

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

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

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