I have a text file here with two values, a name and a score. I have a student struct that has 4 members which are seen below.
I am looking to add the values in the text file to the corresponding members in the struct separating by comma.
First five rows of the students.txt file;
Nubia,Dufrene,70
Louisa,Trippe,49
Aline,Deniz,34
Shery,Munk,63
Angila,Ping,89
My current code;
struct studentType {
string studentFName;
string studentLName;
int testScore;
char grade;
};
int main()
{
vector<studentType> studentVector;
studentType student;
ifstream inFile("students.txt");
while (getline(inFile, student.studentFName, ',' )) {
cout << student.studentFName << endl;
}
printStudents(studentVector);
}
void printStudents(vector<studentType>& passedVect) {
for (studentType element : passedVect) {
cout << element.studentFName << " " << element.studentLName << "\tGrade: " << element.testScore << " (" << element.grade << ")" << endl;
}
}
The FIX I've replaced the while loop with a for loop. I also had to change the struct from int to string for it to work with getline. The simple convertString function uses std::stoi to convert it back to an int as originally planned.
int main()
{
vector<studentType> studentVector;
studentType student;
ifstream inFile("students.txt");
for (studentType i;
getline(inFile, i.studentFName, ',')
&& getline(inFile, i.studentLName, ',')
&& getline(inFile, i.testScore)
; )
{
int testScore = convertString(i.testScore);
i.grade = assignGrade(testScore);
studentVector.push_back(i);
}
printStudents(studentVector);
}
int convertString(string number) {
return stoi(number);
}
Output
Struct Exercises!
Nubia Dufrene Grade: 70 (B)
Louisa Trippe Grade: 49 (D)
Aline Deniz Grade: 34 (F)
Shery Munk Grade: 63 (C)
Angila Ping Grade: 89 (A)
Laila Hollmann Grade: 10 (F)
Sherrill Piller Grade: 47 (D)
Minna Dimitri Grade: 26 (F)
Song Kornreich Grade: 97 (A)
Frank Dammann Grade: 36 (F)
Isaac Abee Grade: 24 (F)
Tiffaney Lukach Grade: 75 (B)
Carmelina Sink Grade: 85 (A)
Matthew Benes Grade: 34 (F)
Fleter Aichele Grade: 78 (B)
Sergio Ewan Grade: 56 (C)
Izetta Armes Grade: 42 (D)
Olen Tee Grade: 89 (A)
Leona Mozee Grade: 54 (D)
Britta Pegrast Grade: 34 (F)
Thanks again!