繁体   English   中英

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

[英]0x20 treated as 0x00 with stringstream

下面的程序将 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';
}

默认情况下, std::stringstream>>运算符跳过写空间。 并且在 ASCII 中(一种典型但绝不是通用的编码)。 0x20是您按下键盘上的那个长按钮时得到的空格字符。

由于 stream 上没有其他内容,因此 NUL 是 output 到c

引入操纵器std::noskipws是解决方法; ss >> std::noskipws >> c; 将值读取为 0x20。

暂无
暂无

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

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