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


当前回答

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

main()
  {
  //your codes 

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

  return 0;
  }

thats所有

其他回答

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

在任何exit()函数之前或main()中的任何return之前添加以下行:

std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");

如果您实际上是在Visual c++中调试应用程序,请按F5或工具栏上的绿色三角形。如果你不是真的调试它(你没有设置断点),按Ctrl+F5或选择菜单上的Start Without debugging(它通常在Debug菜单上,我同意这是令人困惑的)。它会更快一点,更重要的是,它会在结束时暂停,而无需更改代码。

或者,打开命令提示符,导航到exe所在的文件夹,并通过键入它的名称来运行它。这样,当它完成运行时,命令提示符不会关闭,并且您可以看到输出。我更喜欢这两种方法,而不是添加代码,在应用程序完成时停止它。

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

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
}

我只是这样做:

//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更好,但它有点啰嗦,通常没有必要。