c_str fails after a replace string


string fileName;

// fileName is set to xxx-yyy.abc

if (fileName.find('-')) {
replace(fileName.begin(), fileName.end(), '-', '_');
}

So far so good, but a subsequent call to a function only fails when the replace does happen, but works if the replace does not get executed. So obviously replace is doing something I am not aware of. How do I keep c_str() happy?

:

int Parse( filename.cstr() ); // parse will fail when trying to open filename.


Thanks
http://ideone.com/4u5lq , so the code is fine.
The problem must be elsewhere. By the way, find returns the position of the first '-' or string::npos, not true or false, so replace is not called only if fileName starts with '-'.

Why are you constructing an int Parse from a const char* ?

** IGNORE THIS THREAD POST **

I was renaming a filename and then wondering why the file would not open.

NOT what I wanted to do. Not thinkin' get's you in trouble!

*******************************************

Started off with old legacy code, guessed at why c_str() was failing after I added the "replace".

Better problem statement then is:

string fileName;

// fileName can be set to xxx-yyy.abc

replace(fileName.begin(), fileName.end(), '-', '_');

int parseStatus = StringTree.Parse(fileName.c_str());

Within Parse the file open fails, but only when the replace occurred. The problem seems to be that replace has modified the string for c_str()?

Might as well include the line that fails in Parse:

int XmlTreeClass::Parse(const char *const filename)
{

ifstream myfile(filename, ios::nocreate);

if(!myfile.is_open())
{
return (PARSE_OPEN_ERR); // my comment - but only when replace was true.
}
Last edited on
Topic archived. No new replies allowed.