dimanche 1 avril 2018

Using stringstream and stream operator (>>) to put buffer data into specific data types?

As the title says, I'm doing input validation in C++ (in this case, for an int). I'm using a stringstream object to getline from the user, using the stringstream to assign to a variable with the stream operator, like so:

if (sStream >> validInteger) {
    if ((sStream >> input)) {
         code code code
    }
}

So in the first if statement, I'm getting the stringstream object I've created, and putting it into an integer type. If I use the stringstream to put a char into that integer type, the statement will return false and it won't actually assign to the integer, as expected in this situation.

I know that if you try to assign a char literal to an int with the assignment operator, it will just cast to the ASCII int value for that char (like int charInt = 'c' works fine and assigns the ASCII value)

So this means there is logic built into the sStream >> validInteger statement to not cast the data type, and to return false and to not actually assign the data to that variable.

My question is in regards to the logic for this statement. Where is this logic built in? Is the logic to return false and not assign within the stream operator (>>) or the stringstream object?

I've tested this with iostream and fstream objects like cin and ifstream, and they perform the same way. But is this logic built into cin and fstream as well? Or is it just in the stream operator (>>)?

My code is functional and everything works as expected, I just wanted to clarify how C++ operators/objects actually work in this case for my own knowledge.

Aucun commentaire:

Enregistrer un commentaire