How to convert a char array to a string?

C++StringCharArrays

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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;

Solution 2 - C++

Another solution might look like this,

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

which avoids using an extra variable.

Solution 3 - C++

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

Solution 4 - C++

#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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajSanpuiView Question on Stackoverflow
Solution 1 - C++MysticialView Answer on Stackoverflow
Solution 2 - C++stackPusherView Answer on Stackoverflow
Solution 3 - C++YolaView Answer on Stackoverflow
Solution 4 - C++CristianView Answer on Stackoverflow