snippetcppCritical
convert a char* to std::string
Viewed 0 times
charstringconvertstd
Problem
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?Solution
std::string has a constructor for this (see constructor (7)):const char *s = "Hello, World!";
std::string str(s);Note that this constructor deep-copies the character list at
s, and s should not be nullptr; otherwise, the behavior is undefined.Code Snippets
const char *s = "Hello, World!";
std::string str(s);Context
Stack Overflow Q#1195675, score: 531
Revisions (0)
No revisions yet.