To concatenate strings using ostringstream

i want to concatenate two strings in a string or using ostringstream. Like this:

string str= "first string";

ostringstream ostr;
ostr<<"It is a"<<str;

or

string str2 = "it is a"+str;

Please share any easy way.
Thanks in advance.
Sorry, I don't really understand your question... you just listed two ways to concatenate strings... what do you want now?
The first way works. You just have to use ostr.str() to get the string from the stringstream. I think this is overkill for string concatenation because the string class supports it directly.
1
2
3
4
string str = "first string";

ostringstream ostr;
ostr << "It is a" << str;

The second way doesn't work (exactly as typed above) because operator+() is being applied to a string literal (pointer) not a std::string object. This is rather interesting and I hope you study the following examples.
1
2
3
// here's the "verbose" solution
string str = "it is a";
string st2 += str;

 
string st2 = str + "it is a"; // works because there is a str.operator+( const char * ) 

So, this is what you wanted semantically:
 
string st2 = string("it is a") + str;
Actually i tries the first way but it gives an error and i have not tested the second way.
What kind of error(s) are you getting?
I tried but unable to get required result

1
2
3
4
5
6
7
8
9
10
11
12
static string logFileLastName="fileLastName";
string outLogFname = "TestLog";

string test = outLogFname+logFileLastName;
string test2 = string("Debug")+logFileLastName;
string test3 = logFileLastName + outLogFname.c_str();

result:

test= TestLog
test2= Debug
test3 = TestLog


so, it is not printing the other part.

And using ostringstream, it gives errors.


1
2
3
4
5
6
7
8
9
static string str = "first string";

ostringstream ostr;
ostr << "It is a" << str;

 \algommpcbar.cpp(49) : error C2143: syntax error : missing ';' before '<<'
\algommpcbar.cpp(49) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
\algommpcbar.cpp(49) : error C2371: 'ostr' : redefinition; different basic types
1>

Have you #included <sstream> ?

If not, post the exact code you use (as in, the entire function).
Last edited on
The entire file would be even better.
Topic archived. No new replies allowed.