gpt4 book ai didi

strncpy 的 C++ 等价物

转载 作者:太空狗 更新时间:2023-10-29 19:42:32 35 4
gpt4 key购买 nike

C++ 中 strncpy 的等价物是什么? strncpy 在 C 中工作,但在 C++ 中失败。

这是我正在尝试的代码:

string str1 = "hello"; 
string str2;
strncpy (str2,str1,5);

最佳答案

相当于 C 的 strncpy() (顺便说一句,在 C++ 中拼写为 std::strncpy() ,并且在标题中找到 <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

关于strncpy 的 C++ 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681405/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com