
函数strncpy()用于将指定数量的字符从源复制到目标。
以下是strncpy()的语法
char *strncpy( char *destination, char *source, size_t n);
在这里,destination是指向目标数组的指针,源字符串将被复制到该数组中,source是要复制的字符串,n是要从源字符串中复制的最大字符数。
strncpy()函数是不安全的,因为如果在源字符串的前n个字符中没有NULL字符,则目标字符串将不以NULL结尾。
以下是一个演示C++中strncpy()函数的程序。
示例
在线演示
#include <iostream>
#include <cstring>
using namespace std;
int main () {
char source[20] = "This is a string";
char dest[20];
strncpy(dest, source, 4);
cout << "The destination string is: " << dest;
return 0;
}
输出
上述程序的输出如下。
The destination string is: This
现在让我们理解上面的程序。
源字符串包含数据“This is a string”。然后使用 strncpy() 将前四个字符复制到目标字符串中。然后打印目标字符串的内容。显示这一点的
.........................................................