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

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

本文关键字:控制台 包含 cin get 为什么      更新时间:2023-10-16

我刚刚开始使用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;
}
cin >> carrots;

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

cin.ignore();
cin.get();

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

cin >> carrots;

读取CCD_ 7,但留下一个换行符。

cin.get();

读取换行符,程序结束。

cin >> carrots;

获取一个整数输入,并在按enter键后留下一行新行。

cin.ignore();

将其放置在获得输入之后,以避免控制台退出。