Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

c++ - 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...