convert std::ostream to some array?

廉价感情. 提交于 2019-12-24 03:44:08

问题


I have a legacy library that takes data from hardware and writes it to ostream. The method looks like following :

int sensors(ostream*) const;

I am not skilled enough in Ancient Ways. How to convert this data to QByteArray? Or, at least, to char array of known size? I would have solved it myself, but there is an additional problem: the data in ostream seem to be arbitrary length and have several arbitrary '\0' symbols, so you can't count on it being null-terminated.


回答1:


I think this is what OrcunC was getting at:

std::stringstream s;
sensors( &s );
QByteArray( s.str().data(), (int) s.str().size() );

... but hopefully more clear :). See also std::stringstream and std::string for information on the classes/member functions used here. By the way, note that I am using str().data(), not str().c_str() -- I'm being really careful to handle those \0 characters, and I'm not assuming NULL termination.




回答2:


I have not tried it, but you need something like this :

ostream s (ios::out | ios::binary);
//..Populate the stream

//Convert it to string. string can hold \0 values too.
string str = s.str ();

QByteArray ba (str.data (),str.size ());



回答3:


You can subclass std::ostream and use an object of the subclass to collect the bytes into your QByteArray.

/**
 * This helper class collects bytes that are passed to it
 * into a QByteArray.
 *
 * After https://stackoverflow.com/a/19933011/316578
 */
class QByteArrayAppender : public std::ostream, public std::streambuf {
private:
    QByteArray &m_byteArray;
public:
    QByteArrayAppender(QByteArray &byteArray)
        : std::ostream(this),
          std::streambuf(),
          m_byteArray(byteArray) {
    }

    int overflow(int c) {
        m_byteArray.append(static_cast<char>(c));
        return 0;
    }
};

This avoids going via an std::string, which is an extra copy of the byte array.



来源:https://stackoverflow.com/questions/6493841/convert-stdostream-to-some-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!