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

时间:2015-05-13 21:12:50

标签: c++

我正在尝试以用户始终必须输入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;
}

2 个答案:

答案 0 :(得分:3)

iss.str("");

我还建议将其放在while循环中,而不是递归调用函数

答案 1 :(得分:0)

您需要调用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;
}

但是,如果你想要递归,那么你不必担心重置istringstream,因为你永远不会再使用它,下一次递归将使用新的istringstream实例:

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