Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

How can I convert a std::string to a char or a const char?
by

4 Answers

Bharatgxwzm
In the event that you simply need to pass a std::string to a capacity that needs const char you can utilize
std::string str;
const char c = str.c_str();

In the event that you need to get a writable copyy, similar to 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;
MounikaDasa
We can also use string::data function here

#include <iostream>
#include <string>
int main()
{
std::string str = "std::string to const char";
char const
c = str.data();
std::cout << c;
return 0;
}
the above program converts std::string to a pointer of characters to string data
sandhya6gczb
Use the following code to std: string to a pointer of characters or string data

const char p_c_str = x.c_str();
const char* p_data = x.data();
char* p_writable_data = x.data(); // for non-const x from C++17
const char* p_x0 = &x[0];

char
p_x0_rw = &x[0]; // compiles iff x is not const...
sandhya6gczb
Use the following code to std: string to a pointer of characters or string data

const char p_c_str = x.c_str();
const char* p_data = x.data();
char* p_writable_data = x.data(); // for non-const x from C++17
const char* p_x0 = &x[0];

char
p_x0_rw = &x[0]; // compiles iff x is not const...

Login / Signup to Answer the Question.