How to add string to stringstream?

Viewed 1081

I need to merge a lot of strings into one. Something like this

stringstream ss;
string str_one = "hello ";
string str_two = "world!\n";
ss.add(str_one);
ss.add(str_two);


string result = ss.str();

but there is no add function into stringstream. How do I do this?

3 Answers

Very simple, all you have to do:

ss << " appended string";

stringstream has operator<< overload to insert data into the stream. It would return a reference to the stream itself so you can chain multiple insertions.

ss << str_one << str_two;
std::cout << ss.str(); // hello world!

As an alternate, you can leverage fold expression(since C++17) to concatenate multiple strings.

template<typename ...T>
std::string concat(T... first){
    return ((first+ ", ") + ...);
}

int main(){
std::string a = "abc", b = "def", c = "ghi", d = "jkl";
std::cout << concat(a, b, c, d); // abc, def, ghi, 
}

The fold expression is expanded as below:

"abc" + ("def" + ("ghi" + "jkl"));

Demo

You can use str() method like this:

std::string d{};
std::stringstream ss;
ss.str("hello this");

while(std::getline(ss, d)){
    std::cout << d;
};
Related