1

I'm fairly new to c++ and I was wondering why my cin.get() isn't stopping the program in cmd from instantly closing when it's done? I tried the cin.get() on my previous code and it worked, but for some reason it doesn't work on this code.

#include <iostream>

int main()
{
       using namespace std;
       int carrots;
       cout << "How many carrots do you have?" << endl;
       cin >> carrots;
       cout << "You have " << carrots << endl;
       cin.get();
       return 0;
}
David G
  • 94,763
  • 41
  • 167
  • 253
user3720526
  • 123
  • 1
  • 1
  • 7
  • 3
    You still have input in the input buffer. `get` only reads one character. – chris Jul 12 '14 at 02:51
  • i figured it out, I needed to add another cin.get() apparently since the first pauses it when I ask for input and then a second is needed after that. But, what do you mean by input buffer? – user3720526 Jul 12 '14 at 02:53
  • http://www.cplusplus.com/reference/istream/istream/ignore/ – 001 Jul 12 '14 at 02:54
  • I just wrote a function called `holdScreen()` where I use `getline()` to wait for an enter press.s – ChiefTwoPencils Jul 12 '14 at 02:55
  • @user3720526, Input is kept in a buffer and extraction functions take it from there. They don't generally read past what they need to. If you input one `int` and type "23 34", " 34" is still left there. – chris Jul 12 '14 at 02:56

2 Answers2

5

Using cin.get(), you get only one of those characters, treated as char. You would not able see the output as the command prompt will close as soon as the program finishes. Putting cin.get() forces the program to wait for the user to enter a key before it will close, and you can see now the output of your program.

 using namespace std;
       int carrots;
       cout << "How many carrots do you have?" << endl;
       cin >> carrots;
       cout << "You have " << carrots << endl;
       cin.get();
       cin.get();// add another one
       return 0;
bumbumpaw
  • 2,522
  • 1
  • 24
  • 54
5

You have to add

cin.ignore();

Before than

cin.get();

To clean the input buffer from the previously return !

Complete code

#include <iostream>

int main()
{
    using namespace std;
    int carrots;
    cout << "How many carrots do you have?" << endl;
    cin >> carrots;
    cout << "You have " << carrots << endl;
    cin.ignore();
    cin.get();
    return 0;
}
INIM
  • 55
  • 4