将文件数据赋值给结构数组
Assigning file data to array of structs
我正在尝试将输入文件中的一行数据分配给一个结构体数组。
这是我的结构体:
struct student
{
int ID;
int hours;
float GPA;
};
student sStudents[MAX_STUDENTS]; // MAX_STUDENTS = 10
地点:
for (int i = 0; !inputFile.eof(); i++)
{
getline(inputFile, dataLine);
cout << dataLine << endl; // Everything outputs perfectly, so I know dataLine is getting the correct information from getline()
//??
}
在谷歌上爬了一个小时后,我仍然不知道如何将我的getline()数据放入每个struct数组中。
我试过了,
sStudents[i] = dataLine;
sStudents[i] << dataLine;
sStudents.ID = dataLine;
这是我的数据文件:
1234 31 2.95
9999 45 3.82
2327 60 3.60
2951 68 3.1
5555 98 3.25
1111 120 2.23
2222 29 4.0
在这一点上,我变得很沮丧,我只是不知道该做什么。在这一点上,我确信我做得完全不正确,但不确定如何从这里继续。我知道sStudents有10个元素,这很好,但我如何将输入文件中的值分别输入到。id,。hours,。gpa中呢?也许getline()在这里使用不正确? 您可以简单地执行以下操作:
int ID = 0;
int hours = 0;
float GPA = 0.0;
int i = 0;
ifstream inputFile("data.txt");
while (inputFile >> ID >> hours >> GPA)
{
sStudents[i].ID = ID;
sStudents[i].hours = hours;
sStudents[i].GPA = GPA;
i ++;
}
使用标准库的建议。
#include<iostream>
#include<fstream>
#include<vector>
// your data structure
struct Student {
int id;
int hours;
float gpa;
};
// overload the input stream operator
bool operator>>(std::istream& is, Student& s) {
return(is>>s.id>>s.hours>>s.gpa);
}
// not necessary (but useful) to overload the output stream operator
std::ostream& operator<<(std::ostream& os, const Student& s) {
os<<s.id<<", "<<s.hours<<", "<<s.gpa;
return os;
}
int main(int argc, char* argv[]) {
// a vector to store all students
std::vector<Student> students;
// the "current" (just-read) student
Student student;
{ // a scope to ensure that fp closes
std::ifstream fp(argv[1], std::ios::in);
while(fp>>student) {
students.push_back(student);
}
}
// now all the students are in the vector
for(auto s:students) {
std::cout<<s<<std::endl;
}
return 0;
}
使用>>
操作符从输入流中获取数据。所以:
int i;
file >> i;
从文件中提取单个整数。默认情况下,它以空格分隔。使用它,看看你是否更进一步
相关文章:
- C++将文本文件中的数据读取到结构数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- 需要帮助将结构数组传递给函数
- 在 64 位边界上对齐C++结构数组?
- 带有枚举方向/类型的气泡排序结构数组
- 在C++中访问结构数组中的数据
- 从指向结构数组的指针中提取元素
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何在函数中显示结构数组
- 包含作为成员C++函数的结构数组
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- std::transform 将一个结构数组复制到另一个结构数组
- 将非托管结构数组封送到托管数组
- 显示结构数组
- 结构数组中所有类似字段的总和
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何将字符串字符与结构数组进行比较?
- C++结构数组