Greetings so I'm making a program for my CS1 class, and in this program, for some odd reason it'll randomly repeatedly print some values.
For example, I tried 2 students for the printReportCard function and it printed the first one twice and the second one once. Then I tried 3 students, and it printed each one twice in total printing 6 report cards. I have no idea why it's doing this, I've even tried printing vector size and it prints the correct number but for some reason iterates more than once over some report cards. I then checked the text file before it formats it and it had the proper amount of reports but only during that std::for_each
is where it goes wrong oddly enough.
code:
void printReportCard(int numStudents)
{
fstream reportCards;
reportCards.open("reportCard.txt");
string current_card = "2022 First Semester Report Card\n\n";
string name, currentClass, currentGrade;
for (int student = 1; student <= numStudents; student++)
{
getline(reportCards, name);
current_card += "Student Name: " + name + "\n";
current_card += "----------------------------------------------\nCourse:\t\t\tGrade:\n----------------------------------------------\n";
for (int i = 0; i < 7; i++)
{
reportCards >> currentClass >> currentGrade;
current_card += currentClass + getTabs(currentClass) + currentGrade + "\n";
}
string gpa, honorRoll;
reportCards >> gpa >> honorRoll;
if (honorRoll == "!")
{
honorRoll = "You are not on the Honor Roll.";
}
else
{
honorRoll = "You are on the " + honorRoll + " Honor Roll.";
}
current_card += "\nSemester GPA: " + gpa;
current_card += "\n\nHonor Roll: " + honorRoll + "\n\n";
reportCardsVector.push_back(current_card);
system("CLS");
}
reportCards.close();
system("PAUSE");
system("CLS");
reportCards.open("reportCard.txt", ios::trunc | ios::out);
for_each(reportCardsVector.begin(), reportCardsVector.end(), [ & ](const string VALUE) {
reportCards << VALUE << "\n";
cout << VALUE << endl;
});
reportCards.close();
}
text file before format:
Student One
classOne f
classTwo f
classThree f
classFour f
classFive f
classSix f
classSeven f
0
!
Student Two
classOne a
classTwo a
classThree a
classFour a
classFive a
classSix a
classSeven a
High