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

其他回答

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

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


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

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

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

我试着在最后放一个getchar()函数。但这并没有起作用。所以我所做的就是一个接一个地添加两个getchar()函数。我认为第一个getchar()吸收了您在最后一个数据输入后按下的Enter键。所以尝试添加两个getchar()函数而不是一个

而不是按下运行按钮,同时按CTRL和F5,它会给你按任意键继续消息。或者键入“(警告使用此仅用于测试而不是实际程序作为防病毒不喜欢它!!!!)”在你的主函数的末尾但是:(警告使用此仅用于测试而不是实际程序作为防病毒不喜欢它!!!!)

James的解决方案适用于所有平台。

或者在Windows上,你也可以在从main函数返回之前添加以下内容:

  system("pause");

这将运行暂停命令,等待直到你按下一个键,并显示一个漂亮的消息按任意键继续…

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

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
}