5

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.

1
  • 2
    @Mysticial: well, strictly that would be const char* wouldn't it? But I'm guessing that's probably good enough. Commented Dec 25, 2012 at 0:27

1 Answer 1

14

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

6
  • 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
    Commented Dec 25, 2012 at 0:20
  • 3
    @user515430: The requirement is there, it is just well hidden. See this question.
    – Mankarse
    Commented Dec 25, 2012 at 0: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
    Commented Dec 25, 2012 at 1: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
    Commented Dec 25, 2012 at 1:30
  • 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. 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
    Commented Dec 25, 2012 at 9:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.