Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 644
MrDespair Avatar asked Nov 23 '14 19:11

MrDespair


People also ask

Can we use Stringstream in C?

StringStream in C++ is similar to cin and cout streams and allows us to work with strings. Like other streams, we can perform read, write, and clear operations on a StringStream object. The standard methods used to perform these operations are defined in the StringStream class.

How does stringstream work in C++?

The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.

What is stream string?

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.


1 Answers

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.

like image 68
Dietmar Kühl Avatar answered Oct 20 '22 16:10

Dietmar Kühl