How to Convert Char Array to String in C++

  1. Use std::string Constructor to Convert Char Array to String
  2. Use memmove Function to Convert Char Array to String
  3. Use std::basic_string::assign Method to Convert Char Array to String

This article introduces multiple methods to convert a char array to a string container.

Use std::string Constructor to Convert Char Array to String

In this example, we declare a constant C-string, which is then used as a string construct parameter. This method calculates string length automatically. After the constructor call, we can manipulate the tmp_string variable as needed.

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main(){
    const char* c_string = "This will be stored in std::string";

    string tmp_string(c_string);
    cout << tmp_string << endl;

    return EXIT_SUCCESS;
}

Output:

This will be stored in std::string

Use memmove Function to Convert Char Array to String

A more straightforward way is to copy char* data to an initialized string container. This way, you must know the char array length in advance to pass it in the memmove function. Note that string container initialization is critical for correct behavior, and that’s why we are filling the tmp_string variable with 0x01 bytes.

#include <iostream>
#include <string>
#include <cstring>

using std::cout;
using std::cin;
using std::endl;
using std::string;

constexpr int C_STRING_LENGTH = 34;

int main(){
    const char* c_string = "This will be stored in std::string";
    string tmp_string(C_STRING_LENGTH, 1);

    memmove(&tmp_string[0], c_string, C_STRING_LENGTH);
    cout << tmp_string << endl;

    return EXIT_SUCCESS;
}

Note that, you can also copy c_string data to tmp_string using various functions like: memcpy, memccpy, mempcpy, strcpy or strncpy, but do mind carefully reading the manual pages and considering their edge cases/bugs.

Use std::basic_string::assign Method to Convert Char Array to String

Like the previous example, this method requires the length of the char array. We define a char pointer named tmp_ptr and assign the first character’s address in tmp_string to it.

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

constexpr int C_STRING_LENGTH = 34;

int main(){
    const char* c_string = "This will be stored in std::string";
    string tmp_string;

    tmp_string.assign(c_string, C_STRING_LENGTH);
    cout << tmp_string << endl;

    return EXIT_SUCCESS;
}

Related Article - C++ Char

  • How to Convert Int to Char Array in C++
  • How to Convert ASCII to Char in C++
  • Related Article - C++ String

  • How to Parse String Using a Delimiter in C++
  • comments powered by Disqus