296

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
RajSanpui
  • 11,556
  • 32
  • 79
  • 146

5 Answers5

418

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";

// or
str = arr;
Zitrax
  • 19,036
  • 20
  • 88
  • 110
Mysticial
  • 464,885
  • 45
  • 335
  • 332
  • Directly to a string is understood because it's not in array form, but your former one was a `killer` method, which i was looking for. – RajSanpui Jan 22 '12 at 09:17
  • Just a side comment - it is possible to construct a string even from not-null terminated char array if you explicitly set the number of symbols. – Ivaylo Strandjev Jan 22 '12 at 09:19
  • 2
    It would still work either way. The overloaded assignment operator takes a `const char*`, so you can pass it a string literal or char array (which decays to that). – Mysticial Jan 22 '12 at 09:19
  • 3
    @kingsmasher1: Strictly speaking, strings in the form `"hello world"` *are* arrays. If you use `sizeof("hello world")` it will give you the size of the array (which is 12), rather than the size of a pointer (likely 4 or 8). – dreamlax Jan 22 '12 at 09:22
  • @dreamlax: Yes, that i was aware of, but i was trying to see a way to assign an actual array declared like: `char arr[]` to a string, which Mystical gave a great way to do. – RajSanpui Jan 22 '12 at 09:26
  • Just another side comment - if you need to use it in a longer expression, you don't have to construct a named object, this will work just fine: `std::string composite = "Have a " + std::string(arr) + " day"` – penelope Jan 22 '12 at 09:27
  • @penelope: Ahh that was similar to concatenating strings in Java. Again a great one, thanks :) – RajSanpui Jan 22 '12 at 09:29
  • 17
    Note that this only works for **constant** NULL-terminated C-strings. The `string` constructor will not work with, for example, a passed argument string declared as `unsigned char * buffer`, something very common in byte stream handling libraries. – CXJ Mar 27 '14 at 19:12
  • 6
    There's no need for anything being constant. If you have a byte buffer of any char type, you can use the other constructor: `std::string str(buffer, buffer+size);`, but it's probably better to stick to a `std::vector` in that case. – R. Martinho Fernandes Mar 27 '14 at 19:21
  • 4
    Although it might be obvious: `str` is _not_ a convert-function here. It is the name of the string variable. You can use any other variable name (e.g. `string foo(arr);`). The conversion is done by the constructor of std::string that is called implicitly. – Christopher K. Sep 11 '14 at 08:48
  • `error: ‘str’ was not declared in this scope` – Cerin Dec 23 '20 at 19:06
  • Need some clarification on "Note that this only works for constant NULL-terminated C-strings" - what happens if I have a dynamically allocated NULL-terminated c-string? Can I initialize a std::string with such an array and immediately deallocate the array and return the std::string? – Tom Charles Zhang Feb 09 '23 at 04:06
63

Another solution might look like this,

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

which avoids using an extra variable.

Ralph
  • 471
  • 5
  • 14
stackPusher
  • 6,076
  • 3
  • 35
  • 36
  • Could you indicate in the answer how this is different from the accepted answer my Misticial? – Maarten Bodewes Sep 03 '14 at 21:27
  • 1
    @owlstead please see the edit. I simply put my answer because its what I wish I saw when i first came across this page looking for an answer. If someone just as dumb as me comes across this page but isn't able to make that connection from looking at the first answer, i hope my answer will help them. – stackPusher Sep 04 '14 at 18:35
  • This does not work for character arrays in general, only if they are 0-terminated. If you cannot ensure that your character array is 0-terminated, provide a length to the `std::string` constructor like in [this answer](https://stackoverflow.com/a/45129436/11942268). – stackprotector Oct 02 '20 at 08:31
57

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

Yola
  • 18,496
  • 11
  • 65
  • 106
12
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long
Cristian
  • 548
  • 6
  • 8
2

A bit <O/T> based on the OP, but I googled "c++ convert std::array char to string" and it brought me here, yet none of the existing answers deal with std::array<char, ..>:

#include <string>
#include <iostream>
#include <array>
 
int main()
{
  // initialize a char array with "hello\0";
  std::array<char, 6> bar{"hello"};
  // create a string from it using the .data() ptr,
  // this uses the `const char*` ctor of the string
  std::string myString(bar.data());
  // output
  std::cout << myString << std::endl;

  return 0;
}

Output

hello

Demonstration

yano
  • 4,827
  • 2
  • 23
  • 35