[英]Composite std::istream in C++
I have a list of std::istream
objects that I need to appear as a single std::istream
object. 我有一个std::istream
对象列表,我需要将它们显示为单个std::istream
对象。 So if I have three istream
s, A, B and C, I want to be able to create an istream
, D which will first return the bytes from A then the bytes from B, then C before EOF
is reached. 因此,如果我有三个istream
,即A,B和C,我希望能够创建一个istream
,D,它将首先从A返回字节,然后从B返回字节,然后在到达EOF
之前返回C。 The composite stream will always be read sequentially and closed after all bytes are read. 复合流将始终按顺序读取,并在读取所有字节后关闭。
Is there a simple way to do this using stl/boost or do I just need to write my own composite istream? 是否有使用stl / boost做到这一点的简单方法,还是只需要编写自己的复合istream?
The off-topic answer to another question ( https://stackoverflow.com/a/17103292/1424877 ) might help you. 另一个问题的主题外答案( https://stackoverflow.com/a/17103292/1424877 )可能会对您有所帮助。
#include <iostream>
#include <string>
#include <sstream>
class ConcatStreams : public std::streambuf
{
int useBuf;
std::streambuf *sbuf_[2];
char buffer_[1024];
public:
ConcatStreams(std::istream& sbuf1, std::istream& sbuf2) :
useBuf(0), sbuf_{sbuf1.rdbuf(), sbuf2.rdbuf()}
{ }
int underflow()
{
if (this->gptr() == this->egptr()) {
std::streamsize size = 0;
while (useBuf < 2) {
size = this->sbuf_[useBuf]->sgetn(this->buffer_, sizeof this->buffer_);
if (!size) {
useBuf++;
} else {
break;
}
}
this->setg(this->buffer_, this->buffer_, this->buffer_ + size);
}
return this->gptr() == this->egptr()
? std::char_traits<char>::eof()
: std::char_traits<char>::to_int_type(*this->gptr());
}
};
int main()
{
std::istringstream is("hello world!\n");
ConcatStreams cs_(is, std::cin); // prepend "hello world" to the input
std::istream cs(&cs_);
std::string s;
while (cs >> s)
std::cout << "'" << s << "'" << std::endl;
}
Notice that you can't use this particular trick to concatenate std::cin
with itself, or even is
with itself; 请注意,你不能用这种特殊技巧来连接std::cin
与自身,甚至is
与本身; but it should work fine to concatenate any two different input streams. 但将任意两个不同的输入流串联起来应该可以正常工作。 You can even concatenate multiple ConcatStreams
instances! 您甚至可以串联多个ConcatStreams
实例!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.