How to convert a char array to a string? How to convert a char array to a string? arrays arrays

How to convert a char array to a string?


The string class has a constructor that takes a NULL-terminated C-string:

char arr[ ] = "This is a test";string str(arr);//  You can also assign directly to a string.str = "This is another string";// orstr = arr;


Another solution might look like this,

char arr[] = "mom";std::cout << "hi " << std::string(arr);

which avoids using an extra variable.


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:

cout << string("123\0 123") << endl;cout << string("123\0 123", 8) << endl;

Output is:

123
123 123