C++ 函数怎么返回string

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

//Place the function declaration (prototype) below this line
string function(int n);

void main(void)
{
string name;
ofstream fout("D:\\1\\names.dat"); //change the path of the file if necessary

for(int i=1;i<=5;i++)
{
function(i);

// insert a statement below to call the function you write and keep the returned string
// in the string name
fout<<name<<endl;
}
fout.close();

// insert several statements to read the 5 names you have just inputted
// display them on screen, each in one line
ifstream fin("D:\\1\\names.dat");
getline(fin,name);
cout<<name<<endl;
fin.close();

}

string function(int n){
string name;
cout<<endl<<"This function is called "<<n<<" times"<<endl;
cout<<"Please input 5 person's full name(Give name + space + family name):"<<endl;
getline(cin,name);
name.substr();
}
string function(int n){
string name;
cout<<endl<<"This function is called "<<n<<" times"<<endl;
cout<<"Please input 5 person's full name(Give name + space + family name):"<<endl;
getline(cin,name);
name.substr();
}
如何返回name 这个string 阿????

让一个函数返回字符串,让主函数接收使用,有几种方法:

1.通过函数的参数指定一个指针,然后在函数体内对指针赋值。
如:char temp[10];
void func(char *t)
{
strcpy(t, "test");
}
func(temp);即可

2.通过返回值
如:char* func()
{
char *temp = new char[5];
strcpy(temp, "test");
return temp;
}

char *me=func();即可
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-05
直接return name;
关键是返回过去你要保存这个值啊,刚才已经说了
比如
string function(int n){
string name;
cout<<endl<<"This function is called "<<n<<" times"<<endl;
cout<<"Please input 5 person's full name(Give name + space + family name):"<<endl;
getline(cin,name);
return name;
}

调用的时候string name = function(5); // 保存调用结果,也就是function里return name;返回的name本回答被网友采纳
第2个回答  2010-04-05
return name;
不行吗?
相似回答