简体   繁体   English

0x20 被视为 0x00 与字符串流

[英]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?下面的程序将 0x20 写入 stringstream,然后读取该值并且它是 0。为什么会这样以及如何写入一个值以使其被读取为 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.默认情况下, std::stringstream>>运算符跳过写空间。 And in ASCII (a typical but by no means universal encoding).并且在 ASCII 中(一种典型但绝不是通用的编码)。 0x20 is the space character you get when you press that long button on your keyboard. 0x20是您按下键盘上的那个长按钮时得到的空格字符。

As there is nothing else on the stream, NUL is output to c .由于 stream 上没有其他内容,因此 NUL 是 output 到c

Introducing the manipulator std::noskipws is the fix;引入操纵器std::noskipws是解决方法; that is ss >> std::noskipws >> c;ss >> std::noskipws >> c; reads the value as 0x20.将值读取为 0x20。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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