gpt4 book ai didi

c++ - 如何将多组数据存储到一个结构数组中?

转载 作者:行者123 更新时间:2023-11-30 05:43:34 25 4
gpt4 key购买 nike

我的代码旨在接收数据文件并将其存储到结构数组中。截至目前,代码存储了第一个学生的数据,但无法为连续的学生获取任何数据。我如何获取代码以将文件其余部分的数据存储到结构的连续数组中?

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

struct student{
string fname, lname, id, classname[20];
char grade[20];
int units[20], unitstaken, unitscompleted, numberofclasses;
float gpa, points[20], avg;
};

void doesitrun(ifstream& fin, string& filename);
void readit(student& temp, ifstream& fin);
int Read_List(student& child, int size);

int main(){
int i = 0;
ifstream fin;
string filename;
student u[20];
doesitrun(fin, filename);


readit(u[i], fin);
Read_List(u[i], 20);


}

void doesitrun(ifstream& fin, string& filename){
bool trueorfalse;
cout << "Enter file name along with location: ";
getline(cin, filename);
cin.ignore(20, '\n');
fin.open(filename.c_str());
if (fin.fail())
trueorfalse = false;
else
trueorfalse = true;
while (trueorfalse == false){
cout << "File does not run. Please try again. " << endl;
fin.close();
cout << "Enter file name along with location: ";

getline(cin, filename);
fin.open(filename.c_str());
if (fin.fail())
trueorfalse = false;
else
trueorfalse = true;
}

}

void readit(student& temp, ifstream& fin){

int i = 0;
getline(fin, temp.lname, ',');
cin.ignore();
getline(fin, temp.fname);
fin >> temp.id;
fin >> temp.numberofclasses;
fin.ignore(10, '\n');

for (i = 0; i < temp.numberofclasses; i++){

getline(fin, temp.classname[i]);
fin >> temp.grade[i];
fin >> temp.units[i];
fin.ignore(10, '\n');
}

}

int Read_List(student child[], int size)
{
ifstream fin;
int i = 0;

readit(child[i], fin);
while (!fin.eof())
{
i++;
if (i >= size)
{
cout << "Array is full.\n";
break;
}
readit(child[i], fin);
}
fin.close();
return i;
}

最佳答案

可能还有其他与文件格式相关的问题,但是从 Why is iostream::eof inside a loop condition considered wrong ? 开始怎么样?

然后尝试类似的东西,

struct student 
{
//...
friend std::istream & operator >> ( std::istream& is, student& temp ) ;
}

std::istream & operator >> ( std::istream& is, student& temp )
{
readit( temp , is );
return is ;
}

并且在Read_List中,

while ( fin >> child[i] )
{
i++ ;
// ...
}

关于c++ - 如何将多组数据存储到一个结构数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com