I am trying to read from a text file of students and assign each line to a struct data member.
The text file structure is as follows:
Name,Student code, Ability,Consistency,Program name:Subject list
Two students in the file:
Average Ant,204932,50,5,Short course:1
Brilliant Bison,234543,80,3,Bachelor of Bounciness:2,5,3
I can read all of the information to a struct no problem except for the last part(subject list),that are of varying length between students. How can I write code so that if a student only has 1 subject like average ant I can push it into the subjectList vector but if they have 3 like brilliant bison I can still push them all in no problem?
My code:
struct Student
{
string name;
int code;
int ability;
int consistency;
string programName;
vector<int> subjectList;
};
void createStudents(string fileName)
{
string tempSubjectId;
int subjectId;
//temp variable to then use to convert them to int.
string codeTemp, abilityTemp, consistencyTemp;
std::ifstream studentFile(fileName);
//A new student data member is created
Student newStudent;
if(studentFile.is_open() && studentFile.good())
{
cout << " " << endl;
cout << "---Reading from Students---" << endl;
while(getline(studentFile,newStudent.name, ','))
{
//we go get each value which is delimited by a comma and one by a colon
//getline(studentFile, newStudent.name, ',');
//To convert the strings to an int, the string is given to a temporary variable
//Then the temporary variable is parsed to an int using stoi and the code datamember from the struct is assign to that new int
getline(studentFile, codeTemp, ',');
newStudent.code = stoi(codeTemp);
getline(studentFile, abilityTemp, ',');
newStudent.ability = stoi(abilityTemp);
getline(studentFile, consistencyTemp, ',');
newStudent.consistency = stoi(consistencyTemp);
getline(studentFile, newStudent.programName, ':');
//want to push ints into subject list here.
//The new struct data member is added to the vector and returned for further use.
studentList.push_back(newStudent);
}
//file is then closed
studentFile.close();```
good
will fail as well. Actually, there's a conversion operator to bool, returning same value asgood
, so you can simply check:if(studentFile)
– Whirlybird