C++ <cstring> - strncpy() Function
The C++ <cstring> strncpy() function is used to copy the first num characters of the byte string pointed to by source, including the null character, to the character array whose first element is pointed to by destination.
If the end of the source is found before num characters, destination is padded with zeros until a total of num characters is reached. If num is reached before the entire string source was copied, the destination is not null-terminated.
The behavior is undefined if the strings overlap.
Syntax
char * strncpy ( char * destination, const char * source, size_t num );
Parameters
destination |
Specify pointer to the character array where the content is to be copied. |
source |
Specify pointer to the null-terminated byte string to copy from. |
num |
Specify maximum number of characters to copy. size_t is an unsigned integer type. |
Return Value
Returns destination.
Example:
The example below shows the usage of strncpy() function.
#include <iostream> #include <cstring> using namespace std; int main (){ char str1[50] = "xyz"; char str2[50]; char str3[50] = "Hello World!"; //replacing the content of str1 and //str2 with first 5 characters of str3 strncpy(str1, str3, 5); strncpy(str2, str3, 5); cout<<"str1 is: "<<str1<<"\n"; cout<<"str2 is: "<<str2<<"\n"; return 0; }
The output of the above code will be:
str1 is: Hello str2 is: Hello
❮ C++ <cstring> Library