C 库函数 char *strcpy(char *dest, const char *src) 把 src 所指向的字符串复制到 dest。需要注意的是如果目标数组 dest 不够大,而源字符串的长度又太长,可能会造成缓冲溢出的情况。
参数:
dest – 指向用于存储复制内容的目标数组。
src – 要复制的字符串。
返回值
该函数返回一个指向最终的目标字符串 dest 的指针。
例如:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char str1[] = "Sample string";
char str2[40];
char str3[40];
strcpy(str2, str1);//将str1复制给str2
strcpy(str3, "copy successful");
printf("str1: %s\nstr2: %s\nstr3: %s\n", str1, str2, str3);
system("pause");
return 0;
}
执行结果:
其他报错描述:strcpy(Name, name)在类中的使用
解决方法:
一:使用一个头文件
#include <cstring >
二:使用两个头文件
#include <string>
#include <string.h>
源码测试:
#include <iostream>
#include <cstring >
using namespace std;
#define MAX 10
class OBJ
{
private:
char Name[MAX];
int Num;
float Price;
float Total_price;
protected:
public:
void Get_obj(char name[], int num, float price)
{
strcpy(Name, name); // strcpy
Num = num;
Price = price;
Total_price = Price * Num;
}
char *Get_name()
{
return Name;
}
int Get_num()
{
return Num;
}
float Get_price()
{
return Price;
}
float Get_total_price()
{
return Price * Num;
}
};
int main()
{
OBJ ob;
ob.Get_obj("LLL", 10, 10);
cout << ob.Get_name() << endl;
cout << ob.Get_num() << endl;
cout << ob.Get_price() << endl;
cout << ob.Get_total_price() << endl;
cin.get();
return 0;
}
执行结果: