如何将多组数据存储到一系列结构中
How to store multiple sets of data into an array of structures?
我的代码旨在接收数据文件并将其存储到一系列结构中。截至目前,该代码存储了第一个学生的数据,但没有为连续的学生提供任何内容。我将如何获取代码将文件的其余部分存储到结构的连续阵列中?
#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;
}
可能还有其他与文件格式相关的问题,但是从开始,为什么iostream :: eof在环上被认为是错误的?
然后尝试类似的东西,
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# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何将内存分配给一系列指针为结构
- 指向一系列结构中的结构
- 我的一系列结构正在打印垃圾
- 使用libjson创建一系列结构
- 一系列结构似乎不想工作
- 如何将多组数据存储到一系列结构中
- 将一系列结构传递到pthread_create
- 避免复制粘贴代码初始化结构中的一系列SDL_Rect