Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Equivalent of strncpy

Tags:

c++

string

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);
like image 457
Kay Avatar asked Dec 03 '22 09:12

Kay


1 Answers

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
like image 125
sbi Avatar answered Dec 27 '22 04:12

sbi