MrDespair
MrDespair

Reputation: 151

C++ stringstream error handling

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

Upvotes: 12

Views: 13804

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154045

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.

Upvotes: 13

Related Questions