C++ 如何在c+中清除istringstream对象的缓冲区+;?
我试图以用户总是必须输入kg或lb的方式验证输入,如果不这样做,它将要求用户重新输入。它一直工作到那个点,但它不读取新的输入。我知道我需要清除缓冲区,但iss.clear()不起作用C++ 如何在c+中清除istringstream对象的缓冲区+;?,c++,C++,我试图以用户总是必须输入kg或lb的方式验证输入,如果不这样做,它将要求用户重新输入。它一直工作到那个点,但它不读取新的输入。我知道我需要清除缓冲区,但iss.clear()不起作用 float readMass() { string weight; getline(cin, weight); float weightValue; string massUnit; istringstream iss(weight); streampos pos
float readMass()
{
string weight;
getline(cin, weight);
float weightValue;
string massUnit;
istringstream iss(weight);
streampos pos = iss.tellg();
iss >> weightValue >> massUnit;
if (massUnit == "lb")
{
weightValue = weightValue / 2.20462;
}
else if (massUnit == "kg")
{
weightValue = weightValue;
}
else
{
cout << "Please enter a correct weight and mass indicator: \n";
iss.clear();
readMass();
}
return weightValue;
}
float readMass()
{
线重;
getline(cin,重量);
浮动权重值;
弦质量单位;
istringstream iss(重量);
streampos pos=iss.tellg();
iss>>重量值>>质量单位;
如果(质量单位=“磅”)
{
weightValue=weightValue/2.20462;
}
否则,如果(质量单位=“kg”)
{
权重值=权重值;
}
其他的
{
cout
我还建议将其放入while循环中,而不是递归调用函数您需要调用str(“”
)来重置实际缓冲区,还需要调用clear()
来重置错误标志
我建议您将函数实现为一个简单的循环,而不是递归调用,并在每个循环迭代中使用一个新的istringstream
:
float readMass()
{
string weight;
while (getline(cin, weight))
{
float weightValue;
string massUnit;
istringstream iss(weight);
if (iss >> weightValue >> massUnit)
{
if (massUnit == "lb")
return weightValue / 2.20462;
if (massUnit == "kg")
return weightValue;
}
cout << "Please enter a correct weight and mass indicator: \n";
}
return 0.0f;
}
我想您希望在错误情况下返回readMass()
。另请参见和。清除()
是错误标志
float readMass()
{
string weight;
getline(cin, weight);
float weightValue;
string massUnit;
istringstream iss(weight);
if (iss >> weightValue >> massUnit)
{
if (massUnit == "lb")
return weightValue / 2.20462;
if (massUnit == "kg")
return weightValue;
}
cout << "Please enter a correct weight and mass indicator: \n";
return readMass();
}