Click here to Skip to main content
15,845,330 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have craeted following kind of function in a class:

C++
void SetStr(string& s1, string& s2)
 {
 const char* s =(s1+s2).c_str();
 cout<<s<<endl;
 }


On calling it from main nothing is getting printed on console. While the following function works:
C++
void SetStr(string& s1, string& s2)
 {
 cout<<(s1+s2).c_str()<<endl;
 }

Can someone please tell me what is the problem.
Thank you.
Posted
Updated 21-Feb-12 20:38pm
Comments
Chandrasekharan P 22-Feb-12 1:38am    
Please do not repost your question and when you put the code please use pre tags.
jasonterry1 22-Feb-12 3:05am    
umm... your code works for me...
(compiled gcc linux ubuntu)

see here[^]
 
Share this answer
 
Comments
Anitesh Kumar 22-Feb-12 4:07am    
Thank you Emilio...
It should be creating a temp string object in statement s1+s2, so why not put an s3 explicitly?

string st3 = s1+ s2;
const char* ch = st3.c_str();
cout<<ch;


btw, what's wrong with

just cout<<s1+s2 in the first place?
 
Share this answer
 
v2
Comments
CPallini 22-Feb-12 7:35am    
Great Answer, my 5 (applause). BTW you should properly format your code. :-D
Emilio Garavaglia 22-Feb-12 14:51pm    
Done!
CPallini 22-Feb-12 16:20pm    
Così non vale: The youngster should format the code himself.
hi,
try this

C++
s1.append(s2);
cout << s1 <<endl;
 
Share this answer
 
Comments
CPallini 22-Feb-12 7:35am    
Uhm, I see a side effect...
Thank you guys for replies... but my question was not "how can i print the concatinated string?"...It was "What is getting wrong in my code?". I got the answer from Emilio. Please refer that.
 
Share this answer
 
Try This :

C#
void SetStr(string& s1, string& s2)
{
    const char *s;
    strcpy(s,(s1+s2).c_str());
    cout<<s<<endl;
}
 
Share this answer
 
Comments
tolw 22-Feb-12 4:52am    
That's a terrible idea! You are copying a string to an unasigned pointer. No memory has been allocated so the code can have fatal results!
CPallini 22-Feb-12 7:36am    
That's plainly wrong. Please remove it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900