5

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 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

Very simple, all you have to do:

ss << " appended string";

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.