I am having trouble pinpointing where exactly my file input is going wrong. Here is the code:
char tempFirst[20], tempLast[20], tempCourse[7];
char c; // For peeking
// Find out how many students are in the file
inFile >> numStudents;
for (int i = 0; i < numStudents; i++)
{
// Get last name from file
inFile.getline(tempLast, 20, ',');
// Gets rid of any spaces inbetween last and first
while (isspace(inFile.peek()))
c = inFile.get();
// Get first name from file
inFile.getline(tempFirst, 20, '\n');
// New line, get course
inFile >> tempCourse;
// PRINT
cout << tempFirst << "\n" << tempLast << "\n"
<< tempCourse << "\n";
list[i]->SetGrades(inFile);
}
SetGrade leads to one of these three inherited functions:
void EnglishStudent::SetGrades(ifstream& inFile)
{
inFile >> attendance >> project >> midterm >> final;
cout << attendance << " " << project << " " << midterm << " " << final << "\n\n";
}
void HistoryStudent::SetGrades(ifstream& inFile)
{
inFile >> paper >> midterm >> final;
cout << paper << " " << midterm << " " << final << "\n\n";
}
void MathStudent::SetGrades(ifstream& inFile)
{
inFile >> quiz1 >> quiz2 >> quiz3 >> quiz4 >> quiz5
>> test1 >> test2 >> final;
cout << quiz1 << " "<< quiz2 << " " << quiz3 << " " << quiz4 << " " << quiz5
<< " " << test1 << " " << test2 << " " << final << "\n\n";
}
Here is the file I am loading the information in from:
6
Bunny, Bugs
Math 90 86 80 95 100 99 96 93
Schmuckatelli, Joe
History 88 75 90
Dipwart, Marvin
English 95 76 72 88
Crack Corn, Jimmy
Math 44 58 23 76 50 59 77 68
Kirk, James T.
English 40 100 68 88
Lewinsky, Monica
History 60 72 78
Then here is the output:
Bugs
Bunny
Math
90 86 80 95 100 99 96 93
Joe
History
88 75 90
Marvin
English
95 76 72 88
Jimmy
Crack Corn
Math
44 58 23 76 50 59 77 68
James T.
English
40 100 68 88
Monica
History
60 72 78
I am missing most last names and for the first student, firstname has an endline included. How would I go about fixing this?
It’s not that the first name has a newline at the end, it’s that the last name has a newline at the beginning. When the
ints are read from the input, any whitespace encountered that marks the end of theintis left in the input stream.To fix this, either remove whitespace before reading the last name, in the
SetGradesmethods or at the end of the loop. The latter two will also require removing whitespace after readingnumStudents. The easiest way of removing whitespace is with thewsstream manipulator. All it takes is:You can also replace your
peeking loop with this.Replace the character arrays with strings for a more genuine C++ experience. This also necessitates replacing
ifstream::getlinewith thegetlinefree function. As a bonus, your code will work for names longer than 19 characters.