I am trying to port an old program of mine from C to C++. I am having trouble coming up with code to accomplish the task of parsing each line of a file (delimited by semi-colons). I understand that to read each line into a string, I should use std::getline() and have also read solutions involving stringstream. However, I am lost as far as parsing the line into individual variables. Previously, in C, I was using sscanf(). Here is my old code...
void loadListFromFile(const char *fileName, StudentRecordPtr *studentList) {
FILE *fp; // Input file pointer
StudentRecord student; // Current student record being processed
char data[255]; // Data buffer for reading line of text file
// IF file can be opened for reading
if ((fp = fopen(fileName, "r")) != NULL) {
// read line of data from file into buffer 'data'
while (fgets(data, sizeof(data), fp) != NULL) {
// scan data buffer for valid student record
// IF valid student record found in buffer
if (sscanf(data, "%30[^,], %d, %d, %d, %d, %d, %d, %d", student.fullName, &student.scoreQuiz1,
&student.scoreQuiz2, &student.scoreQuiz3, &student.scoreQuiz4, &student.scoreMidOne,
&student.scoreMidTwo, &student.scoreFinal) == 8) {
// Process the current student record into the student record list
processStudentToList(student, studentList);
}
}
}
else {
// Display error
puts("**********************************************************************");
puts("Could not open student record file.");
puts("**********************************************************************");
}
// Close file
fclose(fp);
}
And my current code, which is incomplete as I got stuck on this issue.
void Database::loadFromFile(const string filename) {
ifstream file(filename);
string data;
if ( file.is_open() ) {
cout << "Sucessfully loaded " << filename << ".\n" << endl;
while (getline(file, data)) {
//
}
}
else {
cerr << "Error opening input file.\n" << endl;
}
}
I would greatly appreciate any insight to the C++ equivalent to this approach.
EDIT: The post that this was marked as duplicate of does not answer my question. That solution does not take into account a semi-colon (or any character) delimited string.