views:

2353

answers:

5

C# has a syntax feature where you can concatenate many data types together on 1 line.

string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;

What would be the equivalent in C++? As far as I can see, you'd have to do it all on separate lines as it doesn't support multiple strings/variables with the + operator. This is OK, but doesn't look as neat.

string s;
s += "Hello world, " + "nice to see you, " + "or not.";

The above code produces an error.

+6  A: 
s += "Hello world, " + "nice to see you, " + "or not.";

Those character array literals are not C++ std::strings - you ned to convert them:

s += string("Hello world, ") + string("nice to see you, ") + string("or not.");

To convert ints (or any other streamable type) you can use a boost lexical_cast or provide your own function:

template <typename T>
string Str( const T & t ) {
   ostringstream os;
   os << t;
   return os.str();
}

You can now say things like:

string s = "The meaning is " + Str( 42 );
anon
You only need to explicitly convert the first one: s += string("Hello world,") + "nice to see you, " + "or not.";
Ferruccio
Yes, but I couldn't face explaining why!
anon
boost::lexical_cast - nice and similar on your Str function:)
bb
+3  A: 

boost::format

or std::stringstream

std::strinstream msg;
msg << "Hello world, " << myInt  << niceToSeeYouString;
msg.str(); // returns std::string object
bb
+1 for boost::format
Marcin
+10  A: 
#include <sstream>
#include <string>

std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();

Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm

Paolo Tedesco
A: 

You would have to define operator+() for every data type you would want to concenate to the string, yet since operator<< is defined for most types, you should use std::stringstream.

Damn, beat by 50 seconds...

tstenner
You can't actually define new operators on built-in types like char and int.
Tyler McHenry
+5  A: 

Your code can be written as,

s = "Hello world," "nice to see you," "or not."

...but I doubt that's what you're looking for. In your case, you are probably looking for streams:

std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();
John Dibling
Your 1st example is worth mentioning, but please also mention that it works only for "concatenating" literal strings (the compiler performs the concatenation itself).
j_random_hacker