fixty100
fixty100

Reputation: 11

Visual Studio command prompt closes despite that I tried to stop it with cin.get()

My following basic C++ code isn't working. When I run it in Visual Studio express, it just closes the command prompt after I enter the second number. Thanks in advance.

#include <iostream>

using namespace std;

int main()
{

    int num1, num2, answer;

    cout << " Enter a number: ";
    cin >> num1;
    answer = num1 * num1;
    cout << " the sum of the number is: " << answer << endl;

    cout << "Enter a 2nd number";
    cin >> num2;
    answer = answer + num2;
    cout << "The sum of the two numbers is: " << answer << endl;

    cin.get();
    return 0;
}

Upvotes: 0

Views: 126

Answers (2)

manlio
manlio

Reputation: 18902

The problem is that there are characters left in the input buffer.

Anyway you shouldn't add "tricky" commands to keep the console open (you have to remember to remove them from the "production" code).

You can run your program Without debugger mode (CTRL + F5) and Visual Studio will keep the console application window open until you press a button (just check the settings in Project -> Properties -> Linker -> System -> Sub System -> Console (/SUBSYSTEM:CONSOLE)).

Of course, if you are debugging (F5), a breakpoint on the return 0; is the best option.

Upvotes: 2

rockoder
rockoder

Reputation: 747

This is what is probably happening:

Last cin.get() reads the Enter key that you press after entering the second number. You need one more cin.get() so that the command prompt waits for you to press another key.

Upvotes: 0

Related Questions