Home > Software engineering >  Why does boost::basic_array_source give other values than what I have stored with boost::iostreams::
Why does boost::basic_array_source give other values than what I have stored with boost::iostreams::

Time:10-15

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. 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? The -1 doesn't surprise me that much, it might denote the end of the container. Am I using the classes in a wrong way?

CodePudding user response:

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. 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; (note the sign) and it will become clear.

  • Related