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
posted on 2018-09-10 12:00  一小白  阅读(13592)  评论(0编辑  收藏  举报