Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Console Closing after I've included cin.get()?

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;
}
like image 785
FlowofSoul Avatar asked Jun 18 '11 19:06

FlowofSoul


People also ask

What is the use of CIN get ()?

get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (>>) terminates when whitespace is found.

Does CIN get () Read newline?

getline(char *buffer, int N): It reads a stream of characters of length N into the string buffer, It stops when it has read (N – 1) characters or it finds the end of the file or newline character(\n).

Does CIN end line?

cin is whitespace delimited, so any whitespace (including \n ) will be discarded.

How to declare cin in c++?

The syntax of the cin object is: cin >> var_name; Here, >> is the extraction operator.


2 Answers

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();
like image 182
Xeo Avatar answered Sep 19 '22 19:09

Xeo


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.

like image 40
Nawaz Avatar answered Sep 21 '22 19:09

Nawaz