I'm doing this assignment for class, when I run the code, the last else statement in the last while loop runs before the getline gets input, basically my output looks like this: Enter the name of the file (include extension): grades.txt Options: (enter your selection) Exit, Display average, Display grades, Add new grade Error: Invalid input Options: (enter your selection) Exit, Display average, Display grades, Add new grade
It takes input after all of this but as you can see the statement meant to handle invalid input runs before the getline gets input
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream gradeList;
string fileName;
int tempItem;
vector<int> gradesVector;`your text`
string response;
cout << "Enter the name of the file (include extension): ";
cin >> fileName;
gradeList.open(fileName);
while (!gradeList.is_open()) {
cout << endl << "Error: file doesn't exist." << endl;
cout << "Enter a file name (include extension): ";
cin >> fileName;
gradeList.open(fileName);
}
while (!gradeList.eof()) {
gradeList >> tempItem;
gradesVector.push_back(tempItem);
}
gradeList.close();
cout << "Options: (enter your selection)" << endl;
cout << "Exit, Display average, Display grades, Add new grade" << endl;
getline(cin, response);
while (response != "Exit") {
if (response == "Display average") {
int totalGrades;
int averageGrade;
int i;
totalGrades = 0;
for (i = 0; i < gradesVector.size(); ++i) {
totalGrades = totalGrades + gradesVector[i];
}
averageGrade = totalGrades / (gradesVector.size() + 1);
cout << "The average grade is: " << averageGrade << endl;
cout << "Options: (enter your selection)" << endl;
cout << "Exit, Display average, Display grades, Add new grade" << endl;
getline(cin, response);
}
else if (response == "Display grades") {
int i;
for (i = 0; i < gradesVector.size(); ++i) {
cout << "Grade " << i+1 << ": " << gradesVector[i] << endl;
}
cout << "Options: (enter your selection)" << endl;
cout << "Exit, Display average, Display grades, Add new grade" << endl;
getline(cin, response);
}
else if (response == "Add new grade") {
int newGrade;
newGrade = -1;
while (newGrade < 0 || newGrade > 100) {
cout << "Enter new grade: ";
cin >> newGrade;
cin.clear();
cout << endl;
}
gradesVector.push_back(newGrade);
cout << "Options: (enter your selection)" << endl;
cout << "Exit, Display average, Display grades, Add new grade" << endl;
getline(cin, response);
}
else{
cout << "Error: Invalid input" << endl;
cout << "Options: (enter your selection)" << endl;
cout << "Exit, Display average, Display grades, Add new grade" << endl;
cin.clear();
getline(cin, response);
}
}
}
I really dont know what to try because I can't find anybody with the same issue