9

I've just started learning C++ using C++ Primer Plus but I'm having trouble with one of the examples. Like the book instructed I included cin.get() at the end to prevent the console from closing by itself. However, in this instance it still closes by itself unless I add two cin.get() statements which I don't understand. I'm using Visual Studio Express 2010.

#include <iostream>

int main()
{
    int carrots;

    using namespace std;
    cout << "How many carrots do you have?" << endl;
    cin >> carrots;
    carrots = carrots + 2;
    cout << "Here are two more. Now you have " << carrots << " carrots.";
    cin.get();
    return 0;
}
FlowofSoul
  • 510
  • 7
  • 17

4 Answers4

15
cin >> carrots;

This line leaves a trailing newline token in the input stream, which then gets consumed by the next cin.get(). Just do a simple cin.ignore() directly before that:

cin.ignore();
cin.get();
Xeo
  • 129,499
  • 52
  • 291
  • 397
8

Because cin >> carrots doesn't read the newline which you enter after typying the integer, and cin.get() reads the newline left in the input stream, and then the program ends. That is why the console closes.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
4
cin >> carrots;

reads an int but leaves a newline behind.

cin.get();

reads that newline, and the program ends.

Victor
  • 13,914
  • 19
  • 78
  • 147
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
2
cin >> carrots;

Gets an integer input and leaves a new line after pressing enter key.

cin.ignore();

Place this after getting inputs to avoid the exit of console.

Victor
  • 13,914
  • 19
  • 78
  • 147