concatenate stringstream in c++

concatenate stringstream in c++

本文关键字:c++ in stringstream concatenate      更新时间:2023-10-16

如何连接两个字符串流?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "types.h"    
int main () {
    char dest[1020] = "you";
    char source[7] = "baby";
    stringstream a,b;
    a << source;
    b << dest;
    a << b; /*HERE NEED CONCATENATE*/
    cout << a << endl;
    cout << a.str() << endl;
    return 0;
}

两次尝试的输出如下:

0xbf8cfd20
baby0xbf8cfddc

期望输出为babyyou

应该是:

b << dest;
a << b.str();

stringstream::str返回stringstream中的底层字符串。

a << b.rdbuf();

提供get指针在流的开始,以避免为内容分配另一个std::string

更一般地跨iostreams:

std::istream is1, is2; // eg. (i)stringstream
std::ostream os;       // eg. (o)stringstream
os << is1.rdbuf();
os << is2.rdbuf();
os << std::flush;

这适用于文件流,std::cin等,以及stringstream

您不需要两个std::stringstream实例。一个就够了。

std::stringstream a;
a << source << dest;
std::string s = a.str(); //get the underlying string

问题是"如何连接流",答案解释了如何连接流的内容。下面是一个可以用来将两个istream连接成一个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首先读取第一个streambuf,然后在完成第一个streambuf后读取第二个streambuf。

a << b替换为a << b.str()