为什么 boost::basic_array_source 给出的值不同于我用 boost::iostreams::back_insert_device 存储的值?

Why does boost::basic_array_source give other values than what I have stored with boost::iostreams::back_insert_device?

我正在尝试使用读取和写入 from/to 流的库的函数。为了使我的数据适应该库,我想使用 boost 1.77.0 中的 boost::iostreams。尽管如此,第一个非常简单的例子并没有按预期工作。为什么?

#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 2 和 3 放入字符向量中,因此它们分别以 ASCII 代码 49、50 和 51 的形式落在那里。因此,在初始循环中,您实际上打印的是字符,而不是它们的整数表示。我建议您尝试 std::cout << "Entry: " << +entry << std::endl;(注意 + 号),它会变得清晰。