我刚刚开始使用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) 这与以下内容有关:cin和getline跳过输入但是他们没有回答为什么它只是如何修复它.
为什么cin在缓冲区中留下'\n'但只是cin.getline需要它?
例如:
cin >> foo;
cin >> bar;//No problem
cin >> baz;//No problem.
Run Code Online (Sandbox Code Playgroud)
但随着 cin.getline
cin >> foo;
cin.getline(bar,100);//will take the '\n'
Run Code Online (Sandbox Code Playgroud)
那么为什么它不会发生,cin但它确实如此cin.getline?