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

前端 未结 4 896
眼角桃花
眼角桃花 2020-12-03 18:13

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

相关标签:
4条回答
  • 2020-12-03 18:50
    cin >> carrots;
    

    reads an int but leaves a newline behind.

    cin.get();
    

    reads that newline, and the program ends.

    0 讨论(0)
  • 2020-12-03 18:50
    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.

    0 讨论(0)
  • 2020-12-03 19:00

    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.

    0 讨论(0)
  • 2020-12-03 19:10
    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();
    
    0 讨论(0)
提交回复
热议问题