問題是「如何串接STREAMS」,答案解釋瞭如何連接串流的內容。下面是可被用來連接兩個istreams成一個istream的(文件ConcatStreams.h)一類:
class ConcatStreams
: public std::streambuf {
std::streambuf* sbuf1_;
std::streambuf* sbuf2_;
char* buffer_;
int useBuf;
int bufSize;
public:
ConcatStreams(std::streambuf* sbuf1, std::streambuf* sbuf2)
: bufSize(1024), sbuf1_(sbuf1), sbuf2_(sbuf2), buffer_(new char[bufSize]), useBuf(1) {
}
ConcatStreams(const ConcatStreams& orig);
virtual ~ConcatStreams() { delete[] this->buffer_; }
int underflow() {
if (this->gptr() == this->egptr()) {
// get data into buffer_, obtaining its input from
// this->sbuf_; if necessary resize buffer
// if no more characters are available, size == 0.
std::streamsize size=0;
if(useBuf==1) {
size = this->sbuf1_->sgetn(this->buffer_, bufSize);
if(!size) { useBuf++;}
}
if(useBuf==2) {
size = this->sbuf2_->sgetn(this->buffer_, bufSize);
if(!size) { useBuf++;}
}
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());
}
};
要使用它:
#include "ConcatStreams.h"
istringstream msgIn1("this is a stream.");
istringstream msgIn2("this is another stream.");
ConcatStreams cs(msgIn1.rdbuf(), msgIn2.rdbuf());
istream msgIn(&cs);
cout << "'" << msgIn.rdbuf() << "'" << endl;
基本上類使用流緩衝的從傳遞流創建一個新的streambuf,它首先讀取第一個streambuf,然後在讀完第一個時讀取第二個streambuf。
當然如上所述,在這種情況下,您不需要2個'stringstream's,但是我認爲給出的示例是一些更復雜的用例的普通版本。 – jli
這將創建b的字符串數據的副本;我認爲提問者可能正在尋找一種避免這樣做的方法。 – JasonDiplomat