Hi,
I am having lots of troubles trying to read a file in C++. The main problem I'm having is reading properly the first line of the stream since it is different from all the other lines.
A sample file would be:
#Newbie 101|Exam 1|3
Person One|10
Person Two|20
Person Three|30
the first line starts with a # and declares the class name, assignmanet name and total students.
void Grading::loadData()
{
string filename;
cout << "Enter a filename with records to open: ";
cin >> filename;
std::ifstream file;
file.open(filename.c_str(), std::ios::app);
if (!file) {
cout << "Unable to open the specified file" << endl;
return;
}
string buffer;
vector<Student> students;
vector<Student>::iterator it;
while (!getline(file, buffer, '|').eof()) {
Student stud;
string name;
string tmpgrade;
string course;
string assignment;
int totalstudents;
// read first line
if (buffer.find("#") == 0) {
getline(file, course, '|');
cout << "Course Name : " << course << endl;
cout << "Grading Item : " << assignment << endl;
cout << "Total Students : " << totalstudents << endl;
cout << endl;
continue;
}
getline(file, name, '|');
getline(file, tmpgrade, '|');
double grade = strtod(tmpgrade.c_str(), NULL);
stud.name = name;
stud.grade = grade;
cout << "Name: " << stud.name << endl;
cout << "Grade: " << stud.grade << endl;
students.push_back(stud);
}
I really appreciate any suggestions on how to fix this code to read properly the file. Thanks a lot in advance!