c++ - 如果 'input' 是一个整数,为什么 cin.fail() 会传递 input=100a?

标签 c++ iostream cin

int main(void)
{
   int valid_input();
   int ll_input=0;
   int resp;
   hash_table obj;
   int bucket;  
   while(1)
   {
      ll_input=valid_input();
      if(ll_input>10)
      {
        break;
      }
      obj.insert(ll_input);

   }
   obj.print_ll();


   return 0;
}    

int valid_input()

{
  int input;
  printf("\n\rEnter the value: ");
  std::cin >> input;
  while(std::cin.fail())
  {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    printf("\n\rBad entry!\n\rEnter the value: ");
    std::cin>>input;
  }
  return input;
}

以上是代码,它适用于大多数字母数字组合,它拒绝用户输入,如 a、10aa、1003abc 等。但是,它在 100a、100b 等输入上通过。这可能是什么原因?

以下是快照中的输出 enter image description here

最佳答案

cin >> input 一发现任何非数字就停止读取,因此“100a”被解释为两个标记:“100”和“a”。

“100”被转换为 int 并退出 while(std::cin.fail()) 循环。这使得“a”留在流中,以扰乱 cin 的下一次读取。

捕获这个的快速方法,(在编写和解释方面是快速的,如果输入容易出错,执行起来不是最快的)

std::string token;
while (true) // or a countdown to kick out the truly moronic
{
    cin >> token;
    try
    {
        size_t pos;
        int result = std::stoi(token, &pos);
        if (pos == token.size())
        {
             return result;
        }
    }
    catch (...) // don't really care why std::stoi failed
    {
    }
}

std::stoi documentation.

更快的方法,如果预期会出现错误,请使用 strtol or similar并跳过异常处理开销。

关于c++ - 如果 'input' 是一个整数,为什么 cin.fail() 会传递 input=100a?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35164931/

相关文章:

c# - 平台调用 #define 指令

c++ - 带有参数的方法 (const T *&) or (T * &) or(const T * const &) or(T * const &)

c++ - 当函数名称不带括号发送给cout时,编译器如何确定在运行时输出什么值? C++

使用 ByteArrayStream 时 Java Applet 速度很慢

c++ - 调整双缓冲小部件的大小?

java - JNI 将 Java double 转换为 jdouble 时遇到问题

c++ - 将字符传递给运算符重载的自定义流操纵器

C++ 问题

c++ - 用c++-CIN获取几个整数并将它们放入数组中

c++ - 如何在 C++ 中使用指针创建输入法