为什么输入1.w时下面的验证码卡在cin.ignore上,输入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;
}