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?

The program has finished, so the window closes.

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

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

The program has finished, so the window closes.

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

How can you tell? My eyes aren't that quick. I'm guessing it displays the sum, then exits in a blink.

To the OP, this thread may be of some help. Add a cin.get () or two at the end of the program and see if that helps.

http://www.dreamincode.net/forums/showtopic30581.htm

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

Or just open a command window and run the program from the command line.

Thanks for all of your help on this.

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


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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.