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?
We can convert a char to a string object in java by using the Character. toString() method.
h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.
char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With