Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't stringstream consume output during hex formatting?

Here is a minimal working example:

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;
    unsigned int output;
    
    ss << "0xBB";
    ss >> std::hex >> output;
    std::cout << output << std::endl;
    
    ss << "0xAA";
    ss >> std::hex >> output;
    std::cout << output;
}

I would expect final output to have decimal value of 0xAA, however 2 187 (0xBB) are printed instead. What is the problem here? Shouldn’t stringstream "consume" (move stream pointer) after reading the data?

I expect to have 2 outputs: 0xBB and 0xAA (in decimal format)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that after the first read from the string stream, the stream will be at the "end of file". That is, ss.eof() will be true. It’s not possible to read anything from the file.

This can be checked very easily with e.g.

if (!(ss >> std::hex >> output))
    std::cout << "Failed to read from the stream\n";

You "reset" the state of the stream first, to clear the state. For example with ss.clear():

ss.clear();  // Clear the EOF state
ss << "0xAA";
ss >> std::hex >> output;
std::cout << output;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading