注册 登录
编程论坛 C++教室

自己写的函数 char * str_cat(const char * s1,const char * s2)出错

tomywj 发布于 2010-10-07 11:39, 659 次点击
编写一个函数 char * str_cat(const char * s1,const char * s2); 它带有两个串参数,并返回一个串,该串是两个串参数的合并,要求用new分配结果串的存储。以上是函数要求,以下是我写的程序,拜托各位多多帮忙!先谢谢了!
#include<iostream>
#include<string>
using std::cout;
using std::endl;
char *str_cat(const char *s1,const char *s2)
{
 char *str;
 str=new char[strlen(s1)+strlen(s2)+1];
 if(str==NULL)
   {cout<<"error"<<endl;exit(0);}
 str=(char*)s1;
 while(*str)
    str++;
 while(*s2)
     *str++=*s2++;
 *str='\0';
 return str;      
}
int main()
{
 char *pp,*p1="abc";
 const char *p2="bce";
 pp=str_cat(p1,p2);
 cout<<pp<<"hello!\n";
 delete []pp;
 system("pause");
 return 0;   
}
2 回复
#2
toddyce2010-10-07 12:04
#include<iostream>
#include<string>
using std::cout;
using std::endl;
char *str_cat(const char *s1,const char *s2)
{
char *str;
str=new char[strlen(s1)+strlen(s2)+1];
if(str==NULL)
   {cout<<"error"<<endl;exit(0);}
//str=(char*)s1;
while(*s1)
    *str++=*s1++;
while(*s2)
     *str++=*s2++;
*str='\0';
return str;      
}
int main()
{
char *pp,*p1="abc";
const char *p2="bce";
pp=str_cat(p1,p2);
cout<<pp<<"hello!\n";
delete []pp;
system("pause");
return 0;   
}

try this one..
#3
tomywj2010-10-07 13:09
Thank you! 原来是这样啊!
1