简体   繁体   中英

how to clear the buffer of an istringstream object in c++?

I am trying to validate the input in a way that the user always has to enter kg or lb, if it doesn't do it will ask the user to reenter. It works until that point but it doesn't read the new input. I know that I need to clear the buffer but iss.clear() is not working.

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

iss.str("");

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

You need to call str("") to reset the actual buffer, and also call clear() to reset the error flags.

I would suggest you implement the function as a simple loop instead of a recursive call, and just use a new istringstream on each loop iteration:

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

But, if you want it recursive, then you don't need to worry about resetting the istringstream since you will never be using it again, the next recursion will use a new istringstream instance:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM