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


当前回答

你也可以坚持

while(true)
    ;

or

for(;;)
    ;

最后。

其他回答

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

我通常只在main()的右大括号上加一个断点。当程序以任何方式结束时,断点将出现,您可以ALT-Tab到控制台窗口以查看输出。

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

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

  system("pause");

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

简单的

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

使用#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");
}