0
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() 之前,但并没有改变问题。我用错了吗?

4

4 回答 4

3

您可以重置 my_string 的错误状态:

my_string.clear();
my_string.ignore( /* big number of choice */ );

但我认为每次重新初始化它会更容易:

while(true) {    
    cout << "Enter an integer value of feet." << endl;
    getline(cin, input);
    stringstream my_string(input);
于 2010-09-08T17:15:58.303 回答
1

查看来自 Boost 的 lexical_cast ...

于 2010-09-08T17:18:17.493 回答
0

蛮力解决方案是将您的输入转储到 std::string,然后遍历字符串并检查每个字符是否介于 0 和 9 之间。

这不是最优雅的方法。但这是简单而愚蠢的。:-)

bool isnum(char c)
{
   if(! ( c <= '9' && c >= '0'))
   {  
       return false;
   }
   return true;
}


bool has_int(std::string &s)
{
   for( int i = 0; i < s.length(); i++)
   {
      if( ! isnum(s[i])
      {
         return false;
      }
   }

   return true;
}
于 2010-09-08T17:25:48.607 回答
0

我认为

mystring >> ft

将始终评估为真(如果 mystring 为空,则可能不是)。无论 mystring 是否实际包含数字,该操作仍然有效。

一个想法是

 size_t found=input.find_first_not_of("0123456789 ");
  if (found!=string::npos)
  {
   cout <<   "Invalid input! Please try again."
  }

改编自这里。

于 2010-09-08T17:28:23.600 回答