[英]C++ filling array of structure from file
Hi I need to read a file and get data from file to array of structure. 嗨,我需要读取一个文件,并从文件获取数据到结构数组。
Structure 结构体
struct Activity {
string ID;
string Name;
string quantity; };
I have this function for reading from file 我具有用于从文件读取的功能
int* fillStructure(ifstream &fileActivity){
int i=0;
int numberOfElements = numberOfLines(fileActivity);
Activity* myActivity = new Activity[numberOfElements];
while (i < numberOfElements)
{
getline(fileActivity, myAktivity[i].ID, ',');
getline(fileActivity, myActivity[i].Name, ',');
getline(fileActivity, myActivity[i].quantity, '\n');
i++;
}
fileActivity.close();
return myActivity; }
And when i try in main function to print members of structures It doesnt work 当我尝试使用main函数来打印结构的成员时,它不起作用
int main(){
if (!(fileActivity.is_open())){
cout << "Error when reading file" << endl;
return 0;
}
fillStructure(fileActivity);
cout << myActivity[1].ID << endl; return 0; }
I am beginner, can you guys help me what I am doing wrong ? 我是初学者,你们可以帮我做错什么吗?
您在void fillStructure(ifstream &fileActivity)
声明了myActivity
,但是尝试从int main()
访问。
You have to declare your return value in the main function. 您必须在主函数中声明返回值。
struct Activity {
string ID;
string Name;
string quantitiy;
};
Activity* fillStructure(ifstream &fileActivity) {
int i = 0;
int numberOfElements = numberOfLines(fileActivity);
Activity* myActivity = new Activity[numberOfElements];
while (i < numberOfElements)
{
getline(fileActivity, myActivity[i].ID, ',');
getline(fileActivity, myActivity[i].Name, ',');
getline(fileActivity, myActivity[i].quantitiy, '\n');
i++;
}
fileActivity.close();
return myActivity;
}
int main(){
ifstream fileActivity ("test.txt", ifstream::in);
Activity* retFile;
retFile = fillStructure(fileActivity);
cout << retFile[1].ID << endl;
return 0;
}
Declare the return Type of the fillStructure function in the main function like this: 在主函数中声明fillStructure函数的返回类型,如下所示:
Activity* retFile;
This codesnippet works for me 这个代码片段对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.