为什么在我包括cin.get()后控制台关闭? [英] Why is the Console Closing after I've included cin.get()?
问题描述
我刚刚开始学习C ++使用C ++ Primer Plus,但我有一个例子的麻烦。像书指示,我包括 cin.get()
在结束,以防止控制台自身关闭。但是,在这种情况下,它仍然关闭,除非我添加两个 cin.get()
语句,我不明白。我正在使用Visual Studio Express 2010.
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;
}
推荐答案
cin >> carrots;
此行在输入流中留下尾随的换行符,然后由下一个 cin.get()
。只需在之前直接执行一个简单的 cin.ignore()
:
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();
这篇关于为什么在我包括cin.get()后控制台关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!