简体   繁体   English

为什么 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?

I am trying to use functions of a library that reads and writes from/to streams.我正在尝试使用从/向流读取和写入的库的函数。 To adapt my data to that library, I wanted to use boost::iostreams from boost 1.77.0.为了使我的数据适应该库,我想使用 boost 1.77.0 中的 boost::iostreams。 Still, a first very simple example does not work as expected.尽管如此,第一个非常简单的示例并没有按预期工作。 Why?为什么?

#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;
}

The output is:输出是:

Entry: 1
Entry: 2
Entry: 3
There are 3 bytes.
Read entry 49
Read entry 50
Read entry 51
Read entry -1

Why does it read 49, 50 and 51 instead of 1, 2 and 3?为什么它读作 49、50 和 51 而不是 1、2 和 3? The -1 doesn't surprise me that much, it might denote the end of the container. -1 并没有让我感到惊讶,它可能表示容器的末尾。 Am I using the classes in a wrong way?我是否以错误的方式使用这些课程?

It works correct to me, but not in the intuitive way though.它对我来说是正确的,但不是以直观的方式。 You are putting integers 1 2 and 3 into the vector of chars via stream, so they land there as their ASCII codes, 49, 50 and 51 respectively.您通过流将整数 1 2 和 3 放入字符向量中,因此它们分别作为 ASCII 代码 49、50 和 51 到达那里。 In the initial loop you are actually printing characters, not their integer representations, thus.因此,在初始循环中,您实际上是在打印字符,而不是它们的整数表示。 I suggest you should try std::cout << "Entry: " << +entry << std::endl;我建议你应该尝试std::cout << "Entry: " << +entry << std::endl; (note the + sign) and it will become clear. (注意+号)它就会变得清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM