【问题标题】:Why does boost::basic_array_source give other values than what I have stored with boost::iostreams::back_insert_device?为什么 boost::basic_array_source 给出的值与我用 boost::iostreams::back_insert_device 存储的值不同?
【发布时间】: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


【解决方案1】:

它对我来说是正确的,但不是以直观的方式。您通过流将整数 1 2 和 3 放入 chars 向量中,因此它们分别作为 ASCII 码 49、50 和 51 降落在那里。因此,在初始循环中,您实际上是在打印字符,而不是它们的整数表示。我建议你应该尝试std::cout &lt;&lt; "Entry: " &lt;&lt; +entry &lt;&lt; std::endl;(注意+号),它会变得清晰。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-06
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多