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;
}