头文件
<cstring>
函数原型
char *strncyp(char* destination, const char* source, size_t num);
复制字符串中的字符
将source字符串中的前num个字符复制到destination中。若还没复制完num个字符就发现了source C字符串中包含的结尾符(也就是null字符),则destination会在此处填充0值,之后继续复制还没复制完的字符,直到复制完num个字符为止。
若source字符串不止num个字符,且null字符也没有人为地添加到destination结尾处时,destination不算一个以null结束的C字符串(若强行去读取它则会产生溢出)。
destination和source不应该溢出
参数
destination
指向目的数组的指针,内容会被复制到此处
source
指向源C字符串
num
从source处要复制的最大字符数
size_t为无符号整型
返回值
destination为返回值
实例:
/* strncpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]= "To be or not to be";
char str2[40];
char str3[40];
/* copy to sized buffer (overflow safe): */
strncpy ( str2, str1, sizeof(str2) );
/* partial copy (only 5 chars): */
strncpy ( str3, str2, 5 );
str3[5] = '\0'; /* null character manually added */
puts (str1);
puts (str2);
puts (str3);
getchar();
return 0;
}
编译出现错误:
错误 1 error C4996: 'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. C:\Users\stanway\Documents\Visual Studio 2013\Projects\test\test\test.cpp 46 1 test
解决方法:
属性页->配置属性->C/C++->常规->SDL检查:是改为否
由于使用的是VS2013版本编译,strncpy为老版本函数,而VS2013支持新版本函数,因此报错。其他类似函数错误大都是这个原因。禁用SDL检测即可。
效果:
参考网页:http://www.cplusplus.com/reference/cstring/strncpy/?kw=strncpy