# How to get a const char* or char* from a std::string

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";