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


当前回答

我只是这样做:

//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;

注意:只有在程序早期使用过cin时,才需要清除cin缓冲区。同样使用std::numeric_limits::max()可能比INT_MAX更好,但它有点啰嗦,通常没有必要。

其他回答

简单的

#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 ();2次:

    //...
    cin.get();
    cin.get();
    return 0
}

在代码结束之前,插入这行代码:

system("pause");

这将保持控制台,直到你按下一个键。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    cout << "Please enter your first name followed by a newline\n";
    cin >> s;
    cout << "Hello, " << s << '\n';
    system("pause"); // <----------------------------------
    return 0; // This return statement isn't necessary
}

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

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

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

我在程序的最后一个返回0处设置了断点。它工作得很好。