convert a char* to std::string

Jonathan Prior picture Jonathan Prior · Jul 28, 2009 · Viewed 589.3k times · Source

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?

Answer

Jesse Beder picture Jesse Beder · Jul 28, 2009

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.