convert a char* to std::string


Question

I need to use an std::string to store data retrieved by fgets(). To do this I need to convert the char* return value from fgets() into an std::string to store in an array. How can this be done?

1
224
3/26/2018 10:57:53 PM

Accepted Answer

std::string has a constructor for this:

const char *s = "Hello, World!";
std::string str(s);

Just make sure that your char * isn't NULL, or else the behavior is undefined.

326
7/29/2009 4:58:27 PM

If you already know size of the char*, use this instead

char* data = ...;
int size = ...;
std::string myString(data, size);

This doesn't use strlen.

EDIT: If string variable already exists, use assign():

std::string myString;
char* data = ...;
int size = ...;
myString.assign(data, size);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon