在c ++中连接stringstream

Car*_*low 9 c++ concatenation stringstream

如何连接两个字符串流?

#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;
}
Run Code Online (Sandbox Code Playgroud)

两次尝试中的输出如下:

0xbf8cfd20
baby0xbf8cfddc
Run Code Online (Sandbox Code Playgroud)

期望的输出是babyyou.

jli*_*jli 14

应该:

b << dest;
a << b.str();
Run Code Online (Sandbox Code Playgroud)

stringstream::str返回的底层字符串stringstream.


Mic*_*ker 9

要么

a << b.rdbuf();
Run Code Online (Sandbox Code Playgroud)

只要get指针位于流的开头,以避免std::string为内容分配另一个指针.


Naw*_*waz 6

你不需要两个实例std::stringstream.一个就足够了.

std::stringstream a;
a << source << dest;

std::string s = a.str(); //get the underlying string
Run Code Online (Sandbox Code Playgroud)


seh*_*ehe 5

更常见的是iostreams:

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

os << is1.rdbuf();
os << is2.rdbuf();
os << std::flush;
Run Code Online (Sandbox Code Playgroud)

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