Kemsikov
Kemsikov

Reputation: 572

How to add string to stringstream?

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?

Upvotes: 5

Views: 4698

Answers (3)

Ch3steR
Ch3steR

Reputation: 20669

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

Upvotes: 3

foragerDev
foragerDev

Reputation: 1409

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;
};

Upvotes: 0

Michał Turek
Michał Turek

Reputation: 721

Very simple, all you have to do:

ss << " appended string";

Upvotes: 3

Related Questions