问题描述
如果用户在第一次尝试输入一个数字,下面的代码运行良好。但是,如果他们先输入非数字字符,然后输入数字,则循环永远不会中断,就像我期望的那样。
这是什么原因?
注意:如果我在while循环中声明iss
,它会起作用。虽然感觉有点直观,但我仍然很想知道为什么会这样以及解决此问题的最佳方法是什么。谢谢!
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;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)