将固定长度的数据从std :: istream复制到字符串 [英] copying a fixed length of data from an std::istream to a string

查看:91
本文介绍了将固定长度的数据从std :: istream复制到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将固定长度的数据从std :: istream复制到字符串:

I'd like to copy a fixed length of data from an std::istream to a string:

std::istream & operator >> ( std::istream & is, LogMsg & msg )
{
    // read in 4 bytes - a uint32_t that describes the number of bytes in message:
    // next, read the message bytes into the LogMsg

    typedef std::istream_iterator<unsigned char> Iter;

    Iter            i (is);
    uint32_t        nSize   = 0;
    std::string &   sMsg    = msg.MsgRef();

    is >> nSize;
    sMsg.reserve(nSize);

    std::copy(
        i.begin(), i.begin() + nSize,
        std::back_inserter(sMsg)
    );

    return is;
}

我无法使用此解决方案,因为迭代器上的std :: istream_iterator :: begin()函数仅适用于c ++ 11(我在gcc 4.4.7中仅限于-std = gnu ++ 0x

I can't use this solution, as the std::istream_iterator::begin() function on the iterator is c++11 only (I'm constrained to -std=gnu++0x with gcc 4.4.7

那么,如何将固定长度的数据从输入流复制到字符串中?

So, how can I copy a fixed length of data from an input stream into a string?

我本来喜欢std :: istream :: read,它看起来很合适-它具有以下语法

I originally loooked at std::istream::read, which seems to fit - it has the following syntax

is.read (buffer,length);

但是我认为您不能读入字符串的内部缓冲区,并且我想避免复制到临时缓冲区.我可以以某种方式使用streambuf吗?

But I don't think you can read into the internal buffers of a string and I'd like to avoid a copy to a temporary buffer. Can I use a streambuf somehow?

推荐答案

显而易见的解决方案是std::copy_n:

The obvious solution is std::copy_n:

std::copy_n( std::istreambuf_iterator<char>( is ), size, std::back_inserter( msg ) );

这只有在您可以确定字符在那里时才有效, 然而.如果您在尝试读取文件时遇到文件结尾 字符,未定义的行为随之而来.这意味着尽管它是 一个显而易见的解决方案,可能不是一个好方法.

This will only work if you can be sure that the characters are there, however. If you encounter end of file while trying to read the characters, undefined behavior ensues. Which means that although it is an obvious solution, it maybe isn't a good one.

但是,在C ++ 11中,正式地以及在较早的实现中, 练习时,可以读入内部缓冲区.你必须确保 该字符串具有足够的空间:

However, in C++11, officially, and in earlier implementations, in practice, you can read into the internal buffer. You must make sure that the string has enough space:

msg.resize( size );
is.read( &msg[0], msg.size() );

(由于某种原因,没有非const版本的 std::string::data(),尽管可以保证 C ++ 11.)

(For some reason, there isn't a non-const version of std::string::data(), despite the guarantee of underlying contiguity in C++11.)

这篇关于将固定长度的数据从std :: istream复制到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆