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.

有帮助吗?

解决方案

Just do

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

see std::string constructor link

其他提示

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top