1
#include <iostream>

int main() {

    std::cout << "Please enter two numbers" << std::endl;

    int v1, v2 = 0;

    std::cin >> v1 >> v2;
    std::cout << "The sum of " << v1 << " and " << v2
        << " is " << v1 + v2 << std::endl;

    std::cin.get(); 

    return 0;
}

I added the cin.get() so that I could see the result in the terminal before it closes, but for some reason the program still closes immediately after printing the result. Is there a better way to prevent the window from closing immediately after running the code?

Mdomin45
  • 469
  • 1
  • 6
  • 14
  • 1
    Run the program in a command prompt? – cdhowie Mar 29 '17 at 01:41
  • Sorry I should have specified - I'm compiling and running the code in Visual Studio 2017, so it opens what looks like a terminal, executes the code, and then closes. – Mdomin45 Mar 29 '17 at 01:43
  • 1
    Duplicate of http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input -- add `std::cin.ignore()` before `std::cin.get()` – jwimberley Mar 29 '17 at 01:46
  • 2
    `int v1, v2 = 0;` will assign 0 to `v2` and leave `v1` uninitialized – phuclv Mar 29 '17 at 01:59

1 Answers1

1
std::cin >> v1 >> v2;

At this point you type in, for example:

4 5 <Enter>

(with the <Enter> key generating a newline character).

The first >> parses "4".

The second >> parses "5".

And your call to get() reads the newline character, '\n'.

And then your program immediately terminates.

Moral of the story

Use std::getline() to read a line of text entered interactively, from a terminal, rather than the >> operator. That's what std::getline() is for.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148