To get a const char*
from a std::string
, use its c_str()
method:
const char* pc = s.c_str(); std::cout << pc << "\n";
To get a char*
, you need to make a copy so that it’s safely non-const. Using the buffer of a std::vector
is the easiest way of doing this as the buffer will automatically be deleted when it goes out of scope.
std::string s = "The quick, brown fox jumps over the lazy dog"; std::vector<char> v(s.length() + 1); std::strcpy(&v[0], s.c_str()); pc = &v[0]; std::cout << pc << "\n";
Related
- How to split a string in C++
- How to find a substring in C++
- How to do string formatting in C++
- How to replace all occurrences of a character in a std::string
- How to do case-insensitive string comparison in C++
- How to concatenate a string and an int in C++
- How to convert a string to lower or upper case in C++
- How to trim a std::string in C++
- How to convert an int to a std::string in C++