简体   繁体   中英

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?

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 eg unsigned short or std::uint16_t and then cast to unsigned char .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM