C++ 为什么当我输入1.w时,下面的验证代码卡在cin.ignore上,而当我输入w.1时进入无限循环?
为什么输入时以下验证代码卡在cin.ignore上 1.w,当我输入w.1时进入无限循环?C++ 为什么当我输入1.w时,下面的验证代码卡在cin.ignore上,而当我输入w.1时进入无限循环?,c++,visual-studio-2010,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> /
我试图创建验证数字输入的代码。我已经根据其他帖子的建议创建了代码,但是我仍然有问题
//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;
}
//该代码是用于检查输入是否为数字(浮点或整数)的验证代码。
#包括
#包括
#包括//标准::数值限制
使用名称空间std;
int main()
{
弦线;
浮动金额=0;
布尔标志=真;
//while循环检查输入
while(flag){//检查有效的数字输入
金额、行);
//使用函数的字符串find_first_not_测试数字输入
无符号测试=行。首先查找('0123456789-);
if(test==std::string::npos){//if输入流包含有效输入
首先,'0123456789-。
应该是“0123456789-。”
(注意双引号)。前者是多字节字符文字
当您输入1.w
时:
1
通过cin>>金额提取
.w
通过getline
- 流为空,因此
ignore
等待输入
当您输入w.1
时:
cin>>金额
失败,failbit
设置
getline
流不好时无法提取,因此line
保持为空
test
等于npos
,因此我们从不输入else
块来清除流
- 重复一遍
您从未将标志设置为false
,因此它进入无限循环。getline(cin>>金额,行);
应该是cin>>金额;getline(cin,行);