Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在c+中清除istringstream对象的缓冲区+;?_C++ - Fatal编程技术网

C++ 如何在c+中清除istringstream对象的缓冲区+;?

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

我试图以用户总是必须输入kg或lb的方式验证输入,如果不这样做,它将要求用户重新输入。它一直工作到那个点,但它不读取新的输入。我知道我需要清除缓冲区,但iss.clear()不起作用

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