Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ console program closing before completion.

My Program is a simple sum finder. the code of which I will post at the end. But it asks for the first number. Upon entering it asks you for a second number. After entering the second number, the console window closes before showing the results. When I first build and tested in Visual C++ 2010 it ran fine, but this problem only occurs when running the .exe from the build location. Any tips?

Here is the code If testing yourself please re-assemble:

#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 ;
}
like image 735
user2864157 Avatar asked Apr 29 '26 13:04

user2864157


1 Answers

That's because the window closes when the program is finished running. Use std::cin.get() to keep the window open while it waits for input:

int main()
{
    // ...
    std::cin.get(); // keep the window open; wait for a character
    return 0;
}
like image 191
David G Avatar answered May 02 '26 02:05

David G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!