Q:

How to convert a std::string to const char* or char* in c++?

0

How to convert a std::string to const char* or char*?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

If you just want to pass a std::string to a function, then you can use the below expression.

//Example
std::string str;
const char * c = str.c_str();

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;

NoteThe above code is not exception-safe.

We can also do it with std::vector, it completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');
// get the char* using &writable[0] or &*writable.begin()

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions For Experienced

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< How to access members of the namespace in differen...