3

I'm using VS2012/C++, I need to convert a std::string to char * and I can't find any material online giving any guidance on how to go about doing it.

Any code examples and advice will be greatly appreciated.

Ryan
  • 957
  • 5
  • 16
  • 34
  • 2
    @Mysticial: well, strictly that would be `const char*` wouldn't it? But I'm guessing that's probably good enough. – Component 10 Dec 25 '12 at 00:27

1 Answers1

13

Use

std::string bla("bla");
char* blaptr = &bla[0];

This is guaranteed to work since C++11, and effectively worked on all popular implementations before C++11.

If you need just a const char*, you can use either std::string::c_str() or std::string::data()

rubenvb
  • 74,642
  • 33
  • 187
  • 332
  • 3
    I know C++11 requires the bytes to be contiguous. But I don't see any requirement of the string pointed to by &bla[0] to be zero terminated. That may or may not be important to the user. – user515430 Dec 25 '12 at 00:20
  • 3
    @user515430: The requirement is there, it is just well hidden. See [this question](http://stackoverflow.com/q/7554039/485561). – Mankarse Dec 25 '12 at 00:44
  • 1
    @Mankarse Given the number of comments back and forth, none of them from committee members, I'm not 100% convinced. But why use &bla[0] instead of c_str()? Modifying the std::string using the pointer &bla[0] is just ugly. – user515430 Dec 25 '12 at 01:01
  • I used the method described in the answer and it has worked fine in a function however i'm using it in a different function (pretty much exactly the same) and the output I get is rather strange. The output I get is ­`¡║½½½½½½½½½½½½½½EL)¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■¯■B¶↑h4ë¡║` – Ryan Dec 25 '12 at 01:30
  • The function that is passing the char* onto another function is `for (p = strtok( buffer, "~" ); p; p = strtok( NULL, "~" )) { string jobR(p); char* job = &jobR[0]; parseJobParameters(job); }` and the function that actually displays the output is `int parseJobParameters(char * buffer) { // Parse raw data, should return individual job parameters const char* p; int rows = 0; for (p = strtok( buffer, "|" ); p; p = strtok( NULL, "|" )) { cout<

    – Ryan Dec 25 '12 at 01:33
  • 1
    Using the internal `char*` buffer of the string is perfectly fine and the prime way of calling e.g. Win32 API functions without allocating arrays of `char` yourself. What you have to do, is make sure you allocate enough space in the `string`. As for "proof", see [this answer](http://stackoverflow.com/questions/6077189/will-stdstring-always-be-null-terminated-in-c11). If quotes from the standard plus logical reasoning cannot prove this for you, I give up. Also: stop using `strtok`, especially if you have `std::string` with its numerous `find` functions and `std::stringstream`. – rubenvb Dec 25 '12 at 09:39