Clau
Clau

Reputation: 11

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

Upvotes: 1

Views: 699

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596652

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

Upvotes: 0

user3245832
user3245832

Reputation: 101

iss.str("");

I'd also recommend putting this inside of a while loop instead of recursively calling the function

Upvotes: 3

Related Questions