HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

std::string to char*

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
charstringstd

Problem

I want to convert a std::string into a char* or char[] data type.

std::string str = "string";
char* chr = str;


Results in: “error: cannot convert ‘std::string’ to ‘char’ ...”.

What methods are there available to do this?

Solution

It won't automatically convert (thank god). You'll have to use the method c_str() to get the C string version.

std::string str = "string";
const char *cstr = str.c_str();


.c_str() returns a const char . If you want a non-const char , use .data():

std::string str = "string";
char *cstr = str.data();


Some other options:

-
Copying the characters into a vector:

std::vector cstr(str.c_str(), str.c_str() + str.size() + 1);


Then cstr.data() will give you the pointer.

This version copies the terminating \0. If you don't want it, remove + 1 or do std::vector cstr(str.begin(), str.end());.

-
Copying into a manually allocated array: (should normally be avoided, as manual memory management is easy to get wrong)

std::string str = "string";
char *cstr = new char[str.size() + 1];
std::strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;

Code Snippets

std::string str = "string";
const char *cstr = str.c_str();
std::string str = "string";
char *cstr = str.data();
std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);
std::string str = "string";
char *cstr = new char[str.size() + 1];
std::strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;

Context

Stack Overflow Q#7352099, score: 862

Revisions (0)

No revisions yet.