How can I convert an std::string
to a char*
or a const char*
?
C++ – How to convert a std::string to const char* or char*
ccharconstantsstring
Related Topic
- Java – How to read / convert an InputStream into a String in Java
- Python – Convert bytes to a string
- Javascript – How to make the first letter of a string uppercase in JavaScript
- Javascript – How to convert a string to an integer in JavaScript
- Javascript – How to replace all occurrences of a string in JavaScript
- Javascript – How to check whether a string contains a substring in JavaScript
- Java – How to convert a String to an int in Java
- Java – Why is char[] preferred over String for passwords
Best Answer
If you just want to pass a
std::string
to a function that needsconst char*
you can useIf you want to get a writable copy, like
char *
, you can do that with this:Edit: Notice that the above is not exception safe. If anything between the
new
call and thedelete
call throws, you will leak memory, as nothing will calldelete
for you automatically. There are two immediate ways to solve this.boost::scoped_array
boost::scoped_array
will delete the memory for you upon going out of scope:std::vector
This is the standard way (does not require any external library). You use
std::vector
, which completely manages the memory for you.