-1

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.

  • 4
    Why not just `s1 = pStr;`? `std::string` [has an `operator=` overload for `const char*`](http://en.cppreference.com/w/cpp/string/basic_string/operator%3D). The answers are correct you'd need to resize first to copy one at a time (or use `push_back` or `operator+=` to resize and append for each operation), but why do that work yourself? – ShadowRanger Dec 22 '16 at 17:48
  • 1
    Also, side-note: While some compilers may special case it to avoid the issue, by bog standard C/C++, `for(int i = 0; i < strlen(pStr); i++)` is going to recalculate the length of `pStr` over and over (once each time the condition is tested). Calculate it once outside the loop and save it to a variable and test against that if you must do something like this, or just use pointer arithmetic and stop when `*ptr` is the NUL character (so you scan the string only once, not 1-X times for the length, and one time for copying). – ShadowRanger Dec 22 '16 at 17:52
  • It's strange why you didn't simply try the obvious `s1 = pStr;` first, and then see what results you get. – PaulMcKenzie Dec 22 '16 at 17:52

3 Answers3

6

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;
rocambille
  • 15,398
  • 12
  • 50
  • 68
1

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 };
ilim
  • 4,477
  • 7
  • 27
  • 46
1

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);
smac89
  • 39,374
  • 15
  • 132
  • 179