I have this code that asks for a number input and stores it in a variable. I'm trying to do validation on the input but it's behaving weirdly.
#include <iostream>
using namespace std;
float coursework_mark;
float exam_mark;
float module_mark;
int main() {
//COURSEWORK INPUT WITH VALIDATION
cout << "Please enter your coursework mark: ";
while(!(cin >> coursework_mark)){
cin.clear();
cin.ignore(1000, '\n');
cout << "Invalid data type, please enter valid coursework mark: ";
}
while (coursework_mark < 0 || coursework_mark > 100) {
cout << "Out of range, please enter valid coursework mark: ";
cin >> coursework_mark;
}
//EXAM MARK INPUT WITH VALIDATION
cout << "Please enter your exam mark: ";
while(!(cin >> exam_mark)) {
cin.clear();
cin.ignore(1000, '\n');
cout << "Invalid data type, please enter valid exam mark: ";
}
while (exam_mark < 0 || exam_mark > 100) {
cout << "Out of range, please enter valid exam mark: ";
cin >> exam_mark;
}
//Coursework capping
if (coursework_mark > exam_mark * 2) { coursework_mark = exam_mark * 2;}
//Calculate Module mark
module_mark = (coursework_mark* 0.4) + (exam_mark* 0.6);
//Output results
cout << coursework_mark << endl;
cout << "Your module mark is " << module_mark << endl;
if (module_mark >= 50) {
cout << "Congratulations you have passed!" << endl;
} else if (module_mark < 50) {
cout << "Unfortunately, you have not passed" << endl;
}
}
If user inputs '45kuefggf' the number 45 gets stored as the coursework mark and the code hits the line cout << "Out of range, please enter valid exam mark: ";. I have no idea why it's doing this, how do I make it so that it check if the user input a valid data type?
else ifcould just be anelse.