Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a char* to std::string

Tags:

c++

stdstring

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?

like image 774
Jonathan Prior Avatar asked Jul 28 '09 17:07

Jonathan Prior


People also ask

Can you convert char * to string?

We can convert a char to a string object in java by using the Character. toString() method.

Is std :: string a char *?

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.

Is char * a string?

char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.


2 Answers

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.

like image 175
Jesse Beder Avatar answered Oct 26 '22 03:10

Jesse Beder


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); 
like image 30
Eugene Avatar answered Oct 26 '22 03:10

Eugene