简体   繁体   中英

0x20 treated as 0x00 with stringstream

The following program writes 0x20 to stringstream, then reads the value and it's 0. Why is that and how to write a value so it is read as 0x20?

#include <iostream>
#include <sstream>

int main() {
  std::stringstream ss;
  ss << (char) 0x20;
  char c;
  ss >> c;
  if ( c == 0x20 ) {
    std::cout << "32";
  } else if ( c == 0 ) {
    std::cout << "0";
  } else {
    std::cout << "other";
  }
  std::cout << '\n';
}

By default, std::stringstream 's >> operator skips over writespace. And in ASCII (a typical but by no means universal encoding). 0x20 is the space character you get when you press that long button on your keyboard.

As there is nothing else on the stream, NUL is output to c .

Introducing the manipulator std::noskipws is the fix; that is ss >> std::noskipws >> c; reads the value as 0x20.

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