[try Beta version]
Not logged in

 
Better way to combine strings than "+="?

Sep 13, 2009 at 3:21am
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?
Sep 13, 2009 at 3:27am
Sure, just put it all on one line.

 
string output = "My name is " + name + " and this is " + name2 + " . We're " + profession + "s.\n"
Sep 13, 2009 at 3:32am
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.
Sep 13, 2009 at 3:47am
Oh, I see. It only works if there are strings between every set of constants. Well, that will work for my needs, thanks.
Sep 13, 2009 at 5:11am
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.
Sep 13, 2009 at 8:18am
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 Sep 13, 2009 at 8:23am
Sep 13, 2009 at 10:58am
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.
Sep 13, 2009 at 2:08pm
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.