下面的程序将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
是按下键盘上的长键时得到的空格字符。
由于流上没有其他内容,因此将NUL输出到c
。
解决方法是引入操纵器std::noskipws
;即ss >> std::noskipws >> c;
读取值为0x20。
关于c++ - 使用stringstream将0x20视为0x00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61636836/