C ++控制台程序在完成之前关闭。

时间:2013-10-09 18:26:04

标签: c++ windows console

我的程序是一个简单的求和器。我将在最后发布的代码。 但它要求第一个数字。输入后会询问您第二个号码。 输入第二个数字后,控制台窗口将关闭,然后显示结果。当我第一次在Visual C ++ 2010中构建和测试它运行正常,但只有从构建位置运行.exe时才会出现此问题。有什么提示吗?

以下是代码如果自己测试请重新组装:

#include "stdafx.h" // for Visual Studio users
#include <iostream>

int main()
{
  using namespace std;   
  int no1, no2, sum ;

  cout << "\nEnter the first number = " ;
  cin >> no1 ;

  cout << "\nEnter the Second number = " ;
  cin >> no2 ;

  sum = no1 + no2 ;

  cout << "\nThe sum of "<< no1 <<" and "<< no2 <<" = "<< sum  ; 

  return 0 ;
}

4 个答案:

答案 0 :(得分:2)

保持控制台打开直到你满意为止的一种方法是在它结束时添加一个cin - 在关闭之前它将等待用户关闭它或输入一行输入。

答案 1 :(得分:2)

那是因为程序运行完毕后窗口关闭了。使用std::cin.get()在等待输入时保持窗口打开:

int main()
{
    // ...
    std::cin.get(); // keep the window open; wait for a character
    return 0;
}

答案 2 :(得分:2)

控制台应用程序实际上是指直接从控制台执行。如果直接在它上面运行它们,程序完成后,您将被保留在控制台窗口中,其中包含程序提供的所有输出。 Plus ,您将更习惯使用命令提示符,这有时非常酷且有用。 :-D

如果您对如何在Windows环境中从控制台运行程序有任何疑问,请查看this answer (Compiling C-code from the Command Prompt in Windows?)this one (How to run a c program using command prompt)

答案 3 :(得分:2)

在返回0之前添加cin.get();