user2537688
user2537688

Reputation: 87

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.

Upvotes: 5

Views: 9904

Answers (2)

jogojapan
jogojapan

Reputation: 69967

What the std::copy algorithm does is to copy one source element after the other, and advance the destination iterator after each element.

This assumes that

  • either the size of the destination container has been set large enough to fit all the elements you copy,
  • or you use an iterator type that increases the size of the destination container each time you make an assignment to it.

Therefore, if you want to use the std::copy algorithm, there are two ways of solving this:

  1. Resize the string before making the copies:

    #include <iostream>
    #include <string>
    #include <algorithm>
    
    int main()
    {
      char source[] = "hello world";
    
      std::string dest;
      dest.resize(5);
      std::copy(source,source+5,begin(dest));
    
      std::cout << dest << std::endl;
    
      return 0;
    }
    
  2. Using a back-insert iterator instead of the standard one:

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <iterator>
    
    int main()
    {
      char source[] = "hello world";
    
      std::string dest;
      std::copy(source,source+5,std::back_inserter(dest));
    
      std::cout << dest << std::endl;
    
      return 0;
    }
    

However, as pointed out by others, if the goal is simply to copy the first 5 characters into the string at initialization time, using the appropriate constructor is clearly the best option:

std::string dest(source,source+5);

Upvotes: 1

billz
billz

Reputation: 45410

Just do

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

see std::string constructor link

Upvotes: 18

Related Questions