【发布时间】:2014-11-21 12:32:50
【问题描述】:
我想将固定长度的数据从 std::istream 复制到字符串:
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
那么,如何将输入流中固定长度的数据复制到字符串中呢?
我最初看的是std::istream::read,它似乎很合适——它有以下语法
is.read (buffer,length);
但我不认为你可以读入字符串的内部缓冲区,我想避免复制到临时缓冲区。我可以以某种方式使用流缓冲区吗?
【问题讨论】:
-
AFAIK 在 C++11 中没有
begin()/end()函数用于istream_iterator。 -
流是数据流,而不是容器。