C ++ string stream error handling

I am trying to handle a conversion from string to int using ss.fail and after the program goes back to input it keeps giving error even though I input integers. Note that this only happens after the error loops have been processed. I've tried ss.clear (), cin.ignore, etc. and it still cycles through when I enter an integer. How to handle the error correctly?

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

      

+3


source to share


1 answer


Once a thread is in a crashed state, it will remain in a crashed state until it receives an 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 the string stream does not replace the contents of the string stream! to replace the content of a stream of strings, you can use the method str()

:



ss.str(strNumber);

      

Alternatively, you can create a new stream of lines on each iteration, but this is relatively expensive if many streams are created.

+5


source







All Articles