在c++中strcpy()函数不能用,因C ++strcpy()函数运行不安全,并且具有更安全的函数代替。而取代替strcpy()的函数是strcpy_s(),接下来介绍strcpy_s()具体用法。
首先要包含头文件<cstring>,strcpy_s()函数被包含在此头文件中,此函数不在std名字空间中,记得不要使用语句:using namespace std;。
接着来介绍该函数参数,该函数参数有两种形式,一种为三个参数的strcpy_s(char* a(把复制的内容复制到此指针), int b(复制长度), char const* c(被复制指针));一种为两个参数的strcpy_s(char* a(把复制的内容复制到此指针),char const* c(被复制指针),具体介绍如下
一、两个参数的
#include <iostream>
#include <cstring>
int main()
{
char p[10];
std::cin >> p;
char p1[10];
strcpy_s(p1, p);//数组的数组名是一个常量指针
std::cout << "p1 = " << p1 ;
return 0;
}
运行结果
123//输入的值
p1 = 123
二、三个参数的
#include <iostream>
#include <cstring>
int main()
{
char p[10];
std::cin >> p;
char p1[10];
strcpy_s(p1, 10,p );//10的位置也可以换成strlen(p)+1
std::cout << "p1= " << p1 ;
return 0;
}
运行结果
123//输入的值
p1= 123
注意 1 strlen(p)返回的值为字符串的长度,但是不包括字符串末尾的空字符,所以+1。
注意2 在运用两个参数的strcpy_s()是可能会出错,如
#include <iostream>
#include <cstring>
int main()
{
const char *p="123456";
char *p1=new char[10];
strcpy_s(p1, p);
std::cout << "p1 = " << p1;
delete[]p1;
return 0;
}
运行出错:
1没有与参数列表匹配的 重载函数"strcpy_s"实例;
2."strcpy_s":函数不接受2个参数。
原因:不能保证缓冲区大小
解决方法
方法1、
#include <iostream>
#include <cstring>
int main()
{
const char *p="123456";
char p1[10];//将char *p1更改成 char p1[10]
strcpy_s(p1, p);
std::cout << "p1 = " << p1;
return 0;
}
运行结果
p1=123456
方法2
#include <iostream>
#include <cstring>
int main()
{
const char* p = "123456";
char *p1=new char [10];
strcpy_s(p1,10, p);//使用三个参数的strcpy_s()函数
std::cout << "p1 = " << p1;
delete[] p1;
return 0;
}
运行结果
p1=123456
如有错误,请指出。
如有侵权,请联系删除。