My problem is the following:
- a
const char*is provided to the function in which I would like to perform the operation I am going to describe - what is provided is a filename (full absolute path included) of indeterminate length
- I would like to locate the occurrence of the substring
outputand replace it withinput - the output of these operations must be another
const char*(too much code to change to replace it with astd::string)
What I was thinking to do is the following
string name(filename); //filename is the "const char*" provided by the caller of the function
string portion("output");
name.replace(name.find(insert),insert.length(),"input");
const char* newfilename = (char*)name.c_str();
Now, my questions:
- would do this work?
- is there a better way to obtain what I need?
Thanks to anyone that will help.
Federico
This will work, but you don’t need the cast on
name.c_str()(in fact, it’s wrong:c_str()returns aconst char *).But the pointer you get from
name.c_str()is invalidated as soon as you modifyname, or whennamegoes out of scope. So don’t try returningnewfilenamefrom a function, for instance.If you need it to persist, you have no option but to dynamically allocate memory. Standard practice would be to use a smart pointer to automatically manage deallocation.const char *, you have no option but to manage this yourself. So you could do:
* Well, standard practice would be to use a
std::string! It only gets tricky if you need to interface with a legacy C API.