views:

90

answers:

3

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?

+6  A: 

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();
frunsi
A: 

You can call member functions like operator+= on temporaries. Unfortunately, it has the wrong associativity, but we can fix that with parenthesis.

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

It's a little ugly, but it doesn't involve any unneeded temporaries.

FredOverflow
+2  A: 

You could use boost::format for this:

http://www.boost.org/doc/libs/1_41_0/libs/format/index.html

std::string result = boost::str(
    boost::format("%s and %s sat down with %s, to play cards, while %s played the violin")
      % name1 % name2 % name3 %name4
)

This is is a very simple example of what boost::format can do, it is a very powerful library.

smt