//问题描述: 自己编程实现类似标准库中的strcpy函数
//备注:
//作者: 杨明哲
//完成日期: 2005-03-25
//BUG报告; dearymz@163.com
#include <iostream>
#include <cstdlib>
using namespace std;
namespace ymz//名字空间的使用,防止和标准库的函数冲突
{
//字符串拷贝函数
char* strcpy(char *strDestination, const char *strSource)
{
//对空指针的处理
if(strDestination == NULL || strSource == NULL)
return NULL;
//防止自赋值
if(strDestination == strSource)
return strDestination;
//核心逻辑
for(unsigned int i = 0; ;i++)
{
char c = strSource[i];
strDestination[i] = c;
if(c == '\0')
break;
}
return strDestination;
}
}
const int bufSize = 64;
//测试函数
void main()
{
char *source = new char[bufSize + 1];
char destination[bufSize + 1];
cout<<"请输入源字符串(以回车结束):"<<endl;
cin.getline(source, bufSize);
//开始进行字符串的拷贝处理
ymz::strcpy(destination, source);
//显示处理结果
cout << "Source:\t\t" << source<<endl;
cout << "Destination:\t" << destination <<endl;
//释放内存,防止内存泄露
delete []source;//请注意这里不要写成 delete source.(为什么?)
system("PAUSE");//利用系统提供的任意键退出功能。(这个函数可以用来调用DOS的系统功能)
}
评论