How to convert a char array to a string?

934,062

Solution 1

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

Another solution might look like this,

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

which avoids using an extra variable.

Solution 3

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

#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
Share:
934,062

Related videos on Youtube

RajSanpui
Author by

RajSanpui

Around 9+ years experience into development C, C++, and Linux domain. Also understand Core-Java and consider it as a secondary skill. Currently, in addition to the developer responsibilities, i am also serving the role of DevOps engineer.

Updated on April 16, 2020

Comments

  • RajSanpui
    RajSanpui about 4 years

    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.

  • RajSanpui
    RajSanpui over 12 years
    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.
  • Ivaylo Strandjev
    Ivaylo Strandjev over 12 years
    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.
  • Mysticial
    Mysticial over 12 years
    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).
  • TOMKA
    TOMKA over 12 years
    @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).
  • RajSanpui
    RajSanpui over 12 years
    @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.
  • penelope
    penelope over 12 years
    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"
  • RajSanpui
    RajSanpui over 12 years
    @penelope: Ahh that was similar to concatenating strings in Java. Again a great one, thanks :)
  • CXJ
    CXJ about 10 years
    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.
  • R. Martinho Fernandes
    R. Martinho Fernandes about 10 years
    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<unsigned char> in that case.
  • Maarten Bodewes
    Maarten Bodewes over 9 years
    Could you indicate in the answer how this is different from the accepted answer my Misticial?
  • stackPusher
    stackPusher over 9 years
    @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.
  • Christopher K.
    Christopher K. over 9 years
    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.
  • Assil Ksiksi
    Assil Ksiksi over 6 years
    This is a better answer if you are using std::string as a container for binary data and cannot be certain that the array does not contain '\0'.
  • huseyin tugrul buyukisik
    huseyin tugrul buyukisik over 6 years
    Where is free(tmp)? does string take care of that?
  • Cristian
    Cristian over 6 years
    good question. I think free should be there because I am using malloc.
  • Brian Yeh
    Brian Yeh over 3 years
    Or if the string array does not contain a '\0'
  • stackprotector
    stackprotector over 3 years
    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.
  • Cerin
    Cerin over 3 years
    error: ‘str’ was not declared in this scope