【发布时间】:2021-10-14 14:17:23
【问题描述】:
我正在尝试使用从/向流读取和写入的库的函数。为了使我的数据适应该库,我想使用 boost::iostreams 来自 boost 1.77.0。尽管如此,第一个非常简单的示例并没有按预期工作。为什么?
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>
int main(int, char*[])
{
// Create container
std::vector<char> bytes;
// Set up stream to write three chars to container
boost::iostreams::back_insert_device<std::vector<char>> inserter =
boost::iostreams::back_inserter(bytes);
boost::iostreams::stream stream(inserter);
// Write chars
stream << 1;
stream << 2;
stream << 3;
stream.close();
// Check container
for (char entry : bytes)
{
std::cout << "Entry: " << entry << std::endl;
}
std::cout << "There are " << bytes.size() << " bytes." << std::endl;
// Set up stream to read chars from container
boost::iostreams::basic_array_source<char> source(bytes.data(), bytes.size());
boost::iostreams::stream stream2(source);
// Read chars from container
while (!stream2.eof())
{
std::cout << "Read entry " << stream2.get() << std::endl;
}
return 0;
}
输出是:
Entry: 1
Entry: 2
Entry: 3
There are 3 bytes.
Read entry 49
Read entry 50
Read entry 51
Read entry -1
为什么它读为 49、50 和 51 而不是 1、2 和 3? -1 并不让我感到惊讶,它可能表示容器的结束。我是否以错误的方式使用这些类?
【问题讨论】:
-
流类的模板参数?
-
第一个流将 1 转换为“1”,将 2 转换为“2”。实际上是使用 ascii 表将您的数字转换为文本。
标签: c++ char boost-iostreams