Skeith
Skeith

Reputation: 2542

Convert std::string to char * alternative

I have done a search in google 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?

Upvotes: 1

Views: 11825

Answers (5)

sfpiano
sfpiano

Reputation: 369

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());

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

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.

Upvotes: 12

Jonas B&#246;tel
Jonas B&#246;tel

Reputation: 4482

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!

Upvotes: 1

Rune Aamodt
Rune Aamodt

Reputation: 2611

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());

Upvotes: 6

Tony The Lion
Tony The Lion

Reputation: 63190

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

func(&string[0]);

Upvotes: 0

Related Questions