Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 230
user2537688 Avatar asked Dec 05 '22 10:12

user2537688


1 Answers

Just do

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

see std::string constructor link

like image 117
billz Avatar answered Dec 07 '22 00:12

billz