11

I'm trying to error handle the conversion from string to int using ss.fail and after the program loops back to the input, it keeps giving an error even if I enter integers. Note that this only happens after the error handle loops. I've tried ss.clear(), cin.ignore, etc and it still loops indefinitely when I enter an integer. How do I correctly error handle this?

string strNumber;       //User to input a number
stringstream ss;        //Used to convert string to int
int number;             //Used to convert a string to number and display it

bool error = false;          //Loops if there is an input error

do{
    //Prompts the user to enter a number to be stored in string
    cout << endl << "Enter an integer number: ";
    getline(cin, strNumber);

    //Converts the string number to int and loops otherwise
    ss << strNumber;
    ss >> number;

    if(ss.fail()){
        cout << "This is not an integer" << endl;
        ss.clear();
        //cin.ignore(numeric_limits<streamsize>::max(), '\n');
        error = true;
    }
    else
        error = false;

} while(error == true);
MrDespair
  • 141
  • 1
  • 1
  • 8
  • 2
    You tried to call `ignore` on the wrong stream. It's `ss` that has a non-digit character stuck in it, not `cin`. I suggest you make `ss` a local variable within the loop, so you get a fresh copy each time through. Or, just drop `stringstream` altogether and use `std::stoi` – Igor Tandetnik Nov 23 '14 at 19:32
  • Nevermind, it works perfectly once I did ss.ignore and removed the '\n'. Thanks a lot Igor! – MrDespair Nov 23 '14 at 19:35
  • @Quest `std::to_string` converts the wrong way round - from `int` to `string`. – Igor Tandetnik Nov 23 '14 at 19:37

1 Answers1

12

Once a stream moved into fail state, it will stay in fail state until gets clear()ed. That is, you need to do something like this:

if (ss.fail()) {
    std::cout << "This is not an integer\n";
    ss.clear();
    // ...
}

Also not that just writing to a string stream does not replace the string stream's content! to replace the content of a string stream you can use the str() method:

ss.str(strNumber);

Alternatively you can create a new string stream in each iteration but this is relatively expensive if there are many streams being created.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380