convert a char* to std::string
Solution 1:
std::string
has a constructor for this:
const char *s = "Hello, World!";
std::string str(s);
Note that this construct deep copies the character list at s
and s
should not be nullptr
, or else behavior is undefined.
Solution 2:
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);