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?
11 Answers
I would like to mention a new method which uses the user defined literal s
. This isn't new, but it will be more common because it was added in the C++14 Standard Library.
Largely superfluous in the general case:
string mystring = "your string here"s;
But it allows you to use auto, also with wide strings:
auto mystring = U"your UTF-32 string here"s;
And here is where it really shines:
string suffix;
cin >> suffix;
string mystring = "mystring"s + suffix;
I've just been struggling with MSVC2005 to use the std::string(char*)
constructor just like the top-rated answer. As I see this variant listed as #4 on always-trusted http://en.cppreference.com/w/cpp/string/basic_string/basic_string , I figure even an old compiler offers this.
It has taken me so long to realize that this constructor absolute refuses to match with (unsigned char*)
as an argument ! I got these incomprehensible error messages about failure to match with std::string
argument type, which was definitely not what I was aiming for. Just casting the argument with std::string((char*)ucharPtr)
solved my problem... duh !
Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().
std::string mystring;
mystring = "This is a test!"; // Assign C string to std:string directly
std::cout << mystring << '\n';