Reputation: 87
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
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
Therefore, if you want to use the std::copy
algorithm, there are two ways of solving this:
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;
}
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
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