Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal method to create a large string containing several variables?

I want to create a string that contains many variables:

std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";

std::string sentence;

sentence =   name1 + " and " + name2 + " sat down with " + name3;
sentence += " to play cards, while " + name4 + " played the violin.";

This should produce a sentence that reads

Frank and Joe sat down with Nancy to play cards, while Sherlock played the violin.

My question is: What is the optimal way to accomplish this? I am concerned that constantly using the + operator is ineffecient. Is there a better way?

like image 875
Runcible Avatar asked Dec 23 '22 06:12

Runcible


1 Answers

Yes, std::stringstream, e.g.:

#include <sstream>
...

std::string name1 = "Frank";
std::string name2 = "Joe";
std::string name3 = "Nancy";
std::string name4 = "Sherlock";

std::ostringstream stream;
stream << name1 << " and " << name2 << " sat down with " << name3;
stream << " to play cards, while " << name4 << " played the violin.";

std::string sentence = stream.str();
like image 174
Frunsi Avatar answered Feb 22 '23 22:02

Frunsi