Search code examples
c++file-iocastingunsigned-charistringstream

C++ Reading ints as unsigned chars using istringstream


When using std::istringstream to read gray pixel values from a file (0-255), I notice a strange behavior and I can't understand what is happening.

To conserve memory, I want to read these values into unsigned chars (since they have the same 0-255 range). However, there appears to be some sort of casting/truncation going on.

Input file:

194
194
155
155
124
194

Here is my code:

getline(fp, line); 
unsigned char temp;
istringstream iss(line);
iss >> temp;

When the value in the file is 194, for instance, the integer value for temp is 49...

What type of casting is going on?


Solution

  • There's no casting, this behavior is due to overloading.

    std::basic_istream::operator>> happens to be overloaded for char types, extracting only one character at a time - 1, ASCII value of which is 49. This is the behavior you want, when you're reading single characters and it's assumed, that you want exactly that, when you're extracting to a character type.

    To read the text as whitespace-delimited numbers, you have to use a larger type for the extraction e.g. unsigned short or std::uint16_t and then cast to unsigned char.