ユーザーが番号を入力するまで、繰り返し番号を入力するように求めようとしています。
ユーザーが最初の試行で数字を入力すると、以下のコードは正常に実行されます。ただし、最初に数字以外の文字を入力してから数字を入力すると、期待どおりにループが中断されることはありません。
これの理由は何ですか?
注: iss
while ループ内で宣言すると機能します。少し直感的に感じますが、なぜそうなのか、この問題に取り組む最善の方法は何かを知りたいと思っています. ありがとう!
int main() {
std::istringstream iss;
int age = 0;
while (true){
std::string myStr;
std::getline(cin, myStr); // note: clearing entire line as need cin empty for next bit of code
iss.str(myStr);
if (iss >> age){
break; // iss >> age fails even if the user inputs a number (if first enter a non-numeric value).
}
else{
continue;
}
}
return 0;
}