Click here to Skip to main content

standard c_str() problem in C++

Sign Up to vote bad
good
See more: C++
I have craeted following kind of function in a class:

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:
void SetStr(string& s1, string& s2)
 {
 cout<<(s1+s2).c_str()<<endl;
 }
Can someone please tell me what is the problem.
Thank you.
Posted 21 Feb '12
Edited 21 Feb '12

Comments
Chandrasekharan P - 22 Feb '12
Please do not repost your question and when you put the code please use pre tags.
jasonterry1 - 22 Feb '12
umm... your code works for me... (compiled gcc linux ubuntu)

see here[^]
  Permalink  
Comments
Anitesh Kumar - 22 Feb '12
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?
  Permalink  
Comments
CPallini - 22 Feb '12
Great Answer, my 5 (applause). BTW you should properly format your code. :-D
Emilio Garavaglia - 22 Feb '12
Done!
CPallini - 22 Feb '12
Così non vale: The youngster should format the code himself.
hi,
try this
 
s1.append(s2);
cout << s1 <<endl;
  Permalink  
Comments
CPallini - 22 Feb '12
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.
  Permalink  
Try This :
 
void SetStr(string& s1, string& s2)
{
    const char *s;
    strcpy(s,(s1+s2).c_str());
    cout<<s<<endl;
}
  Permalink  
Comments
tolw - 22 Feb '12
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
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)

add
  Print Answers RSS
Your Filters
Interested
Ignored
     
  1. OriginalGriff (1,245)
  2. Sandeep Mewara (1,037)
  3. VJ Reddy (545)
  4. SAKryukov (473)
  1. Sandeep Mewara (13,934)
  2. OriginalGriff (12,986)
  3. SAKryukov (8,004)
  4. VJ Reddy (5,145)
  5. losmac (5,065)


Advertise | Privacy | Mobile
Web01 | 2.5.120515.1 | Last Updated 22 Feb 2012
Copyright © CodeProject, 1999-2012
All Rights Reserved. Terms of Use
Layout: fixed | fluid