void get_english_input() {
string input = " ";
stringstream my_string(input);
int ft;
double in;
while(true) {
cout << "Enter an integer value of feet." << endl;
getline(cin, input);
my_string << input;
if(my_string >> ft)
break;
cout << "Invalid input! Please try again." << endl;
}
cout << "you entered " << ft << " as the int value for feet." << endl;
/*while(true) {
cout << "Enter a double value of inches." << endl;
getline(cin, input);
my_string << input;
break;
cout << "Invalid input! Please try again." << endl;
}
cout << "we are done entering english input" << endl;
cout << "feet = " << ft << endl;
cout << "inches = " << in << endl;*/
}
此代码应该通过尝试将 my_string 的内容放入 ft 来测试输入是否为整数。如果我输入字母而不是整数,则会收到错误消息“输入无效!请重试”,这就是应该发生。问题是,在我收到该消息一次后,即使下一个输入有效,我也会为之后的每个输入获得它。
有人建议我应该使用std::cin.clear(); 清除错误标志。我尝试将它放在 getline() 之前,但并没有改变问题。我用错了吗?