What is the equivalent of strncpy
in C++? strncpy
works in C, but fails in C++.
This is the code I am attempting:
string str1 = "hello";
string str2;
strncpy (str2,str1,5);
The equivalent of C's strncpy()
(which, BTW, is spelled std::strncpy()
in C++, and is to found in the header <cstring>
) is std::string
's assignment operator:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With