Search code examples
c++arraysstringcopystrncpy

Copy length of characters from array to std::string


I am trying to copy 5 characters from a character array into a std::string

char name[] = "Sally Magee";
std::string first;
copy(name, name + 5, first.begin()); //from #include <algorithm>
std::cout << first.c_str();

However I get the string plus a whole bunch of unprintable characters that I do not want. Any ideas? Thanks.


Solution

  • Just do

    char name[] = "Sally Magee";
    std::string first(name, name + 5);
    std::cout << first << std::endl;
    

    see std::string constructor link