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


当前回答

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

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
}

其他回答

只需在返回0之前使用cin.ignore();两次

main()
  {
  //your codes 

  cin.ignore();
  cin.ignore();

  return 0;
  }

thats所有

调用cin.get ();2次:

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

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

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

如果你使用的是Windows,为什么不直接从控制台运行这个程序呢?这样,程序结束后窗口仍保持打开状态。

[编辑]:当我使用KDevelop4时,IDE底部的一个选项卡中运行着一个完整的Bash实例(一个Linux CLI)。这就是我在这种情况下使用的方法。