問題描述
我剛剛開始使用 C++ Primer Plus 學習 C++,但我在其中一個示例中遇到了問題.就像書中指示的那樣,我在末尾包含了 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() 后控制臺會關閉?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!