c++ - 为什么下面的验证代码输入1.w时会卡在cin.ignore上,输入w.1时会进入无限循环?

标签 c++ visual-studio-2010

为什么我输入下面的验证码会卡在cin.ignore上 1.w 并在输入 w.1 时进入无限循环?
我正在尝试创建验证数字输入的代码。我已经根据其他帖子中给出的建议创建了代码,但仍然遇到问题。

//The code is validation code used to check if input is numerical (float or integer). 
#include <iostream>
#include <string>
#include <limits> // std::numeric_limits
using namespace std;
int main ()
{
    string line;
    float amount=0;
    bool flag=true;

//while loop to check inputs
while (flag){ //check for valid numerical input
    cout << "Enter amount:";
    getline(cin>>amount,line);
//use the string find_first_not_of function to test for numerical input
    unsigned test = line.find_first_not_of('0123456789-.');

    if (test==std::string::npos){ //if input stream contains valid inputs
        cout << "WOW!" << endl;
        cout << "You entered " << line << endl;
        cout << "amount = " << amount << endl;
    }

    else{ //if input stream is invalid
        cin.clear();
        // Ignore to the end of line
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
  }

    return 0;
}

最佳答案

首先,'0123456789-.' 应该是 "0123456789-." (注意双引号)。前者是多字节字 rune 字。

当您输入1.w时:

  • 1 通过 cin>>amount 提取。
  • .w 通过 getline 提取
  • 流为空,因此忽略等待输入

当您输入w.1时:

  • cin>>amount 失败,failbit 已设置
  • getline 当流损坏时无法提取,因此 line 保持为空
  • test 等于 npos,因此我们永远不会进入 else block 来清除流
  • 重复一遍

关于c++ - 为什么下面的验证代码输入1.w时会卡在cin.ignore上,输入w.1时会进入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16117554/

相关文章:

c++ - OpenGL - 纹理显示不正确(夹紧?)

c++ - OpenGL - 某些图形卡上的问题

c++ - Visual Studio 2010 中未解析的外部符号

c++ - 使用迭代器将 std::vector 附加到它自己的元素

c - 这个汇编代码生成完整了吗?

c# - 选项卡插件 - 无法将选项卡右对齐 (Asp.net)

asp.net-mvc - Visual Studio 2010 Web 发布缺少文件

c++ - 在 QML 文件中使用 C++ 类变量

c++ - std::function 检查类的继承

c++ - 如何在 Mac OSX C++ 中查找任何进程的 PID