strncpy

头文件

<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





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值