他の人が指摘しているように、問題は入力ストリームに余分な '\n' 文字があることです。
一般的な回答とは反対に、現在の入力をフラッシュ (ignore()) することは良い解決策ではないと思います。あなたは問題ではなく症状を治療しています。ignore() を使用している場合、実際に必要なユーザー入力や、ユーザーからのエラーを検出した可能性のあるものを破棄している可能性があります。
> Input Your age
> 36xxxx
// If you use
std::cin >> age;
// Then sometime later in your code you use
// ignore to make sure that you have "correctly" skipped to the next new line
std::ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// You have now just ignored the fact that the user typed xxx on the end of the input.
// They were probably doing that to force an error in the code or something else erroneous
// happened but you just missed it with std::ignore()
最善の解決策は、このような状況に陥らないことです。この問題は、と
の組み合わせを使用してユーザー入力を解析することによって発生します。通常または通常の入力を解析するために使用するのが大好きです。しかし、手動のユーザー入力 (つまり、質問/回答) は予測が難しく、ユーザー入力は予測が困難です(<enter> を押すとバッファーがフラッシュされるため、入力は '\n' 文字で終了します)。operator<<()
std::getline()
operator<<()
line based
その結果、解析するときmanual user input
は常に std::getline() を使用します。このようにして、私は彼らの答え全体を得たことを知っています. また、入力を検証して入力エラーがないことを確認することもできます。
std::cout << "What is your age\n";
std::string line;
std::getline(std::cin, line); // Get user input
// Use stream for easy parsing.
std::stringstream linestream(line);
// Get value we want.
linestream >> age;
// Validate that we have not thrown away user input.
std::string error;
linestream >> error;
if (error.length() != 0) { /* do stuff to force user to re-input value */ }