Better way to combine strings than "+="?

I've been writing a lot of programs lately that have to put together a lot of strings, an it's kind of a pain to have to write them like
1
2
3
4
5
6
7
string output = "My name is ";
output += name;
output += " and this is ";
output += name2;
output += ".  We're ";
output += profession;
output += "s.\n";


Is there a command I could use to combine all the components of the output string at once?
Sure, just put it all on one line.

 
string output = "My name is " + name + " and this is " + name2 + " . We're " + profession + "s.\n"
Huh. Could of sworn I tried that a long time ago and got an error. I'll give it another shot thanks, thanks very much.
Oh, I see. It only works if there are strings between every set of constants. Well, that will work for my needs, thanks.
It should work even if you have two "constants" (which I assume you mean the name, name2, and profession) without a string between, as long as there is a + there.

The name and name2 are replaced with strings (the ones you have obviously stored in there earlier), and you're just concatenating strings together.
It works as long as one of the first two you are adding together are strings. For example, you can do this:

1
2
string s1 = "hello";
string s2 = s1 + "test";


But you can't do this:

 
string s = "hello" + "test";


But you can solve that by passing the first string literal to the string constructor:

 
string s =  string("hello") + "test" + "add as many as you want";
Last edited on
Use std::ostringstream rather than manipulating strings directly. You can directly write type as long as it has an std::ostream operator or is a built in type.
If all you want is to concatenate strings, stick with Chewbob's example. There is no need to involve the machinery of an ostream for that.

However, if you plan to do formatted conversions, then you will need to do as kbw suggests:
1
2
3
ostringstream oss;
oss << "Hello" << ' ' << "world" << ' ' << 42;
cout << oss.str() << endl;
Topic archived. No new replies allowed.