C++中函数strcpy和strcpy_s

strcpy:
语法:

 #include <string.h>
  char *strcpy( char *to, const char *from );

  
  
  • 1
  • 2
  • 3

功能:复制字符串from 中的字符到字符串to,包括空值结束符。返回值为指针to。由于没有字符串长度的限制,所以复制过程中遇到过长的字符串可能会发生未知的错误。

strcpy_s:
语法:

#include<string.h>
errno_t __cdecl strcpy_s(char*_Destination,rsize_t _SizeInBytes,char const* _Source);
  
  
  • 1
  • 2

功能:复制字符串_Source中的字符到字符串_Destination,其中限制了大小为_SizeInBytes,这是为了防止字符串过长超出缓存区内存引发问题而要求的。

在VS2015中使用strcpy的时候会给出error C4996: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.这样我们可以按照上面的语法换成使用strcpy_s,也可以选择不产生警告,在程序开头加上

#define _CRT_SECURE_NO_WARNINGS
  
  
  • 1

即可,但要注意字符串不可太长。

实例1(strcpy_s):

#include<iostream>
#include<string>
using namespace std;
const int N = 2;
void main()
{
    char *strings[N];
    char str[80];
    cout << "At each prompt, enter a string:\n";
    for (int i = 0; i < N; i++) {
        cout << "Ener a string #" << i << ":";
        cin.getline(str, sizeof(str));
        strings[i] = new char[strlen(str) + 1];
        strcpy_s(strings[i], strlen(str) + 1, str);
    }
    cout << endl;
    for (int i(0); i < N; i++)
        cout << "String #" << i << ":" << strings``

] << endl;
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

实例2(strcpy):

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
const int N = 2;
void main()
{
    char *strings[N];
    char str[80];
    cout << "At each prompt, enter a string:\n";
    for (int i = 0; i < N; i++) {
        cout << "Ener a string #" << i << ":";
        cin.getline(str, sizeof(str));
        strings[i] = new char[strlen(str) + 1];
        strcpy(strings[i], str);
    }
    cout << endl;
    for (int i(0); i < N; i++)
        cout << "String #" << i << ":" << strings[i] << endl;
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值