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