将字符长度从数组复制到std :: string

use*_*688 3 c++ arrays string copy strncpy

我试图将5个字符从字符数组复制到 std::string

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

但是我得到了字符串加上一大堆我不想要的不可打印的字符.有任何想法吗?谢谢.

bil*_*llz 12

做就是了

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

请参阅std :: string构造函数链接

  • 或者:`std :: string first(name,5);` (2认同)