开发者

Convert std::string to char * alternative

I have done a search in google开发者_如何学Python and been told this is impossible as I can only get a static char * from a string, so I am looking for an alternative.

Here is the situation: I have a .txt file that contains a list of other .txt files and some numbers, this is done so the program can be added to without recompilation. I use an ifstream to read the filenames into a string.

The function that they are required for is expecting a char * not a string and apparently this conversion is impossible.

I have access to this function but it calls another function with the char * so I think im stuck using a char *.

Does anyone know of a work around or another way of doing this?


In C++, I’d always do the following if a non-const char* is needed:

std::vector<char> buffer(str.length() + 1, '\0');
std::copy(str.begin(), str.end(), buffer.begin());
char* cstr = &buffer[0];

The first line creates a modifiable copy of our string that is guaranteed to reside in a contiguous memory block. The second line gets a pointer to the beginning of this buffer. Notice that the vector is one element bigger than the string to accomodate a null termination.


You can get a const char* to the string using c_str:

std::string str = "foo bar" ;
const char *ptr = str.c_str() ;

If you need just a char* you have to make a copy, e.g. doing:

char *cpy = new char[str.size()+1] ;
strcpy(cpy, str.c_str());


As previous posters have mentioned if the called function does in fact modify the string then you will need to copy it. However for future reference if you are simply dealing with an old c-style function that takes a char* but doesn't actually modfiy the argument, you can const-cast the result of the c_str() call.

void oldFn(char *c) { // doesn't modify c }
std::string tStr("asdf");
oldFn(const_cast< char* >(tStr.c_str());


There is c_str(); if you need a C compatible version of a std::string. See http://www.cppreference.com/wiki/string/basic_string/c_str

It's not static though but const. If your other function requires char* (without const) you can either cast away the constness (WARNING! Make sure the function doesn't modify the string) or create a local copy as codebolt suggested. Don't forget to delete the copy afterwards!


Can't you just pass the string as such to your function that takes a char*:

func(&string[0]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜