Before the sum is given, the program closes. What's causing this?

#include <iostream>  

//function main
int main()
{
    //var declarations
    int number1;
    int number2;
    int sum;
    
    std::cout << "Enter first number: ";
    std::cin >> number1; //read first integer from user into number1
    
    std::cout << "Enter second number: ";
    std::cin >> number2; //read second integer from user into number2
    
    sum = number1 + number2; //add numbers stored in int's, store total in sum
    
    std::cout << "Sum is " << sum << std::endl;
    
    return 0;
}

worked perfectly ok for me

Enter first number: 10
Enter second number: 20
Sum is 30
Press any key to continue . . .

Perhaps its the compiler you are using -- what compiler and operating system?

Rashakil, it closes on me before it ever displays the sum.

Acient D, I'm using Dev C++ on Win XP.

Yes with Dev-C++ you have to add code at the bottom of the function to prevent main() from immediately returning to the OS. cin.get() (c++) or getchar() will normally do the trick.

you could also add system ("PAUSE"); right before you return from main. This will cause the program to stop and wait for a key to be hit before it closes. You would do this instead of cin.get() .

you could also add system ("PAUSE"); right before you return from main. This will cause the program to stop and wait for a key to be hit before it closes. You would do this instead of cin.get() .

cin.get () is preferred. The link I posted before explains how to clear the buffer before cin.get () .

Walt P wrote this on system ("PAUSE") .

http://www.gidnetwork.com/b-61.html

HEY GUYS I HAVE THE SAME PROBLEM BUT IN BORLAND C++,,,,,,,,


I AM COMPILIND C PROGRAM ,,,,,,,,,,,,,

DOES cin.get () WORK IN C ???????????????????????????????

This article has been dead for over six months. Start a new discussion instead.