C++ 字符串 12-- 18.34~35.函数如何返回字符串

#include <iostream>
#include <string>
using namespace std;
char *get(const char *p);
/*---------------------------------
     18.34~35.函数如何返回字符串
---------------------------------*/
int main()
{
char ch[10];
char *p;
cout<<"请输入名字:";
cin>>ch;
p=get(ch);
cout<<"名字是:"<<p<<endl;
delete []p;//记得释放get()申请的内存
//delete p;//遮掩的话,只能释放p指向的第一个元素


p=get("Jack"); //传递未命名字符串
cout<<"名字是:"<<p<<endl;
delete []p;


char *p1="Mike";
p=get(p1); //传递指向未命名字符串的指针
cout<<"名字是:"<<p<<endl;
delete []p;


return 0;
}


char *get(const char *ch)
{
char *p=new char[strlen(ch)+1];
strcpy(p,ch);
cout<<ch;
return p;

}

运行结果:

请输入名字:nose
nose名字是:nose
Jack名字是:Jack
Mike名字是:Mike
Press any key to continue

猜你喜欢

转载自blog.csdn.net/paulliam/article/details/80540321