2011-06-18 32 views
8

我刚刚开始使用C++ Primer Plus学习C++,但是我遇到了其中一个例子。就像本书指示的那样,我在末尾包含了cin.get()以防止控制台自行关闭。但是,在这种情况下,除非我添加两个我不明白的陈述,否则它本身仍然会关闭。我使用Visual Studio Express的2010为什么控制台在我包含cin.get()之后关闭?

#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; 
} 
+0

GetChar();可能有帮助 ? –

回答

12
cin >> carrots; 

这条线离开输入流,然后把它由下一个cin.get()消耗在尾随的换行符令牌。只要做一个简单的cin.ignore()直接之前:

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

因为cin >> carrots不读,你typying整数后进入换行,cin.get()读取新行的输入流中离开,然后程序结束。这就是控制台关闭的原因。

2
cin >> carrots; 

读取int但留下一个换行符后面。

cin.get(); 

读取该换行符,程序结束。

1
cin >> carrots; 

获得一个整数输入并在按下回车键后留下一个新行。

cin.ignore(); 

在获取输入以避免控制台退出后放置此位置。

相关问题