-1

Possible Duplicate:
How to stop C++ console application from exiting immediately?

So im learning c++ and i was given this example and i wanted to run it. But i cannot get it to stay up, unless i change it. How do i get Microsoft visual 2010 to keep up the screen when it gets to the end of the program after I release it?

#include<iostream>
using namespace std;

int area(int length, int width);        /* function declaration */

/* MAIN PROGRAM: */
int main()
{
    int this_length, this_width;      

    cout << "Enter the length: ";             /* <--- line 9 */
    cin >> this_length;
    cout << "Enter the width: ";
    cin >> this_width;
    cout << "\n";                             /* <--- line 13 */

    cout << "The area of a " << this_length << "x" << this_width;
    cout << " rectangle is " << area(this_length, this_width);

    return 0;
}
/* END OF MAIN PROGRAM */

/* FUNCTION TO CALCULATE AREA: */
int area(int length, int width)   /* start of function definition */
{
    int number;

    number = length * width;

    return number;
}                                 /* end of function definition */
/* END OF FUNCTION */
Community
  • 1
  • 1
Dakota
  • 1
  • 1
  • 1
  • 2
  • 1
    This very question was previously asked here: http://stackoverflow.com/questions/2529617/how-to-stop-c-console-application-from-exiting-immediately (there are several solutions listed there). – James McNellis Apr 27 '10 at 23:26

5 Answers5

5

In Visual C++ you can either:

  • Put a breakpoint at the closing brace of main and run attached to the debugger (Debug -> Start Debugging). When the breakpoint is hit you will be able to view the console window.
  • Run detached from the debugger (Debug -> Start Without Debugging). When the application terminates, the console window will stay open with a "Press any key to continue..." prompt.
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • I tried "start without debugging" but it still closes on me... – Dakota Apr 27 '10 at 23:35
  • 1
    @Dakota: Make sure your application is a console application (Project Properties -> Configuration Properties -> Linker -> System -> SubSystem should be "Console (/SUBSYSTEM:CONSOLE)"). – James McNellis Apr 27 '10 at 23:38
2

I usually use cin.getchar() to wait for a character.

Michael Dorgan
  • 12,453
  • 3
  • 31
  • 61
1

Try adding system("PAUSE"); to the end of main before the return statement.

This executes the PAUSE system command which waits for a key to be pressed.

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361
1

The easiest way is to wait for the user to press a key before returning from main.

redtuna
  • 4,586
  • 21
  • 35
1

You already have the answer in your code.. add another cin at the end of your program ;P user would have to press enter for program to continue and exit

Jonas B
  • 2,351
  • 2
  • 18
  • 26