为什么在我包含cin.get()后控制台关闭?

Flo*_*oul 9 c++ visual-studio-2010

我刚刚开始使用C++ Primer Plus学习C++,但我遇到了其中一个例子的问题.就像我指示的那本书一样,我cin.get()在最后包括了防止控制台自行关闭.但是,在这种情况下,它仍然自行关闭,除非我添加两个cin.get()我不理解的语句.我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

Xeo*_*Xeo 15

cin >> carrots;
Run Code Online (Sandbox Code Playgroud)

此行在输入流中留下一个尾随换行符号,然后由下一个使用cin.get().在此cin.ignore()之前直接做一个简单的事情:

cin.ignore();
cin.get();
Run Code Online (Sandbox Code Playgroud)


Naw*_*waz 8

因为cin >> carrots在读取整数后没有读取你输入的换行符,并且cin.get()读取输入流中剩下的换行符,然后程序结束.这就是控制台关闭的原因.