什么是strncpyC++中的等价物?strncpy在C中工作,但在C++中失败.
这是我正在尝试的代码:
string str1 = "hello";
string str2;
strncpy (str2,str1,5);
Run Code Online (Sandbox Code Playgroud)
sbi*_*sbi 10
相当于C strncpy()(其中,BTW,拼写std::strncpy()在C++中,并且在标题中找到<cstring>)是std::string赋值运算符:
std::string s1 = "Hello, world!";
std::string s2(s1); // copy-construction, equivalent to strcpy
std::string s3 = s1; // copy-construction, equivalent to strcpy, too
std::string s4(s1, 0, 5); // copy-construction, taking 5 chars from pos 0,
// equivalent to strncpy
std::string s5(s1.c_str(), std::min(5,s1.size()));
// copy-construction, equivalent to strncpy
s5 = s1; // assignment, equivalent to strcpy
s5.assign(s1, 5); // assignment, equivalent to strncpy
Run Code Online (Sandbox Code Playgroud)
您可以在的某个版本上使用basic_string::copy,或者使用std::copy,它可以使用指针作为输入迭代器。std::stringconst char*
顺便问一下,“strncpy 在 C++ 中失败”是什么意思?