I realize there are similar questions to this however, those solutions seem to only work if a group of data is on the same line.
I have some data structured in text file like so:
<string student name>
<string course>
<float mark>
...
Every 3 lines is a new student, with a total of 6 students. My code works until it gets to the part where it assigns a mark, which I need to read in as a float
, everything else is a string.
I;ve found that getline()
won't do this for me, wondering what is the best way to work with mixed types from a text file?
#include <iomanip>
#include <ios>
#include <iostream>
#include <iterator>
#include <list>
#include <fstream>
struct Student {
std::string name;
std::string course;
std::string grade;
float mark;
};
int main() {
Student students [6];
std::string filename = "data.txt";
std::ifstream file(filename);
int i = 0;
while(getline(file, students[i].name))
{
getline(file, students[i].course);
getline(file, students[i].mark);
if (students[i].mark > 89.5) {
students[i].grade = "HD";
} else {
students[i].grade = "PASS";
}
++i;
}
return 0;
}