C++ - copying from const char* to string

16.4k views Asked by At

Is there a way to copy string from const char* to string in C++? I'm trying to do something like this:

#include <iostream>
#include <string.h>

using namespace std;

int main(){

    string s1;
    const char* pStr = "Sample Text";

    for(int i = 0; i < strlen(pStr); i++)
        s1[i] = pStr[i];

    cout<<s1<<endl;

    return 0;
}

In my case s1 turns out to be empty.

3

There are 3 answers

0
rocambille On BEST ANSWER

Take a look in cppreference, the constructors of std::basic_string (the template class behind std::string), alternative (5):

const char* pStr = "Sample Text";
string s1(pStr);

cout<<s1<<endl;
0
ilim On

You should either initialize s1 to have a size equal to strlen(pStr) or just append each character to s1.

Initiating s1 with a specific size would be as the line of code given below.

string s1(strlen(pStr));

Similarly, appending each character would be as follows.

for(int i = 0; i < strlen(pStr); i++)
    s1.push_back(pStr[i]);

However, unless you have a specific reason to investigate each character, I would recommend not using a loop at all, and initiating s1 as follows.

string s1{ pStr };
2
smac89 On

C++11

#include <algorithm>
#include <iterator>

string s1;
const char* pStr = "Sample Text";

std::copy(pStr, pStr + strlen(pStr), std::back_inserter(s1));

Another way:

string s1;
const char* pStr = "Sample Text";

s1.assign(pStr);