Converting a C++ string
to a char array is pretty straightorward using the c_str
function of string and then doing strcpy
. However, how to do the opposite?
I have a char array like: char arr[ ] = "This is a test";
to be converted back to:
string str = "This is a test
.
Another solution might look like this,
which avoids using an extra variable.
OUT:
There is a small problem missed in top-voted answers. Namely, character array may contain 0. If we will use constructor with single parameter as pointed above we will lose some data. The possible solution is:
Output is:
The
string
class has a constructor that takes a NULL-terminated C-string: