字符串流和二进制数据
stringstream and binary data
为了 read/write 二进制数据 to/from std::basic_stringstream 需要什么(某些方法覆盖?)?
我正在尝试以下代码,但它没有像我想象的那样工作:
std::basic_stringstream<uint64_t> s;
uint64_t a = 9;
s << a;
uint64_t b;
s >> b;
std::cout << b << std::endl;
但我打印了“0”(使用 GCC 构建)。
如果你想read/write 二进制数据你不能使用<<
或>>
你需要使用std::stringstream::read
和 std::stringstream::write
函数。
您还需要使用 <char>
专业化,因为只有 char
可以安全地别名其他类型。
所以你可以这样做:
std::stringstream ss;
std::uint64_t n1 = 1234567890;
ss.write((char const*) &n1, sizeof(n1)); // sizeof(n1) gives the number of char needed
std::uint64_t n2;
ss.read((char*) &n2, sizeof(n2));
std::cout << n2 << '\n';
输出:
1234567890
为了 read/write 二进制数据 to/from std::basic_stringstream 需要什么(某些方法覆盖?)? 我正在尝试以下代码,但它没有像我想象的那样工作:
std::basic_stringstream<uint64_t> s;
uint64_t a = 9;
s << a;
uint64_t b;
s >> b;
std::cout << b << std::endl;
但我打印了“0”(使用 GCC 构建)。
如果你想read/write 二进制数据你不能使用<<
或>>
你需要使用std::stringstream::read
和 std::stringstream::write
函数。
您还需要使用 <char>
专业化,因为只有 char
可以安全地别名其他类型。
所以你可以这样做:
std::stringstream ss;
std::uint64_t n1 = 1234567890;
ss.write((char const*) &n1, sizeof(n1)); // sizeof(n1) gives the number of char needed
std::uint64_t n2;
ss.read((char*) &n2, sizeof(n2));
std::cout << n2 << '\n';
输出:
1234567890