"Gary Wessle" <ph****@yahoo.comwrote in message
news:87************@yahoo.com...
Hi
after reading the docs, I was hoping this would work, but I can't find
out why.
....you can't find out why you were hoping it would work?
....you can't find out why it did work?
What do you mean?
string a = "I ";
string b = "am";
int ego;
if(sentence.find((a+b).c_str(),0)!= string::npos) ego++;
The call to c_str() there will cause you headaches. (a+b) creates a
temporary string, which will be destroyed when it is no longer needed. This
can be after the call to c_str() but before the call to find(); in which
case, the pointer returned by c_str() will point to memory which has since
been deallocated. This is a bad thing.
One way to solve this problem is to make an explicit temporary:
string tmp = a + b;
if(sentence.find(tmp.c_str(),0)!=string::npos) ego++;
this works because tmp lasts until the end of the current scope.
A better solution, which others have posted elsethread, is to leave out the
call to c_str() entirely.
Philip