Reputation: 53
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?
Upvotes: 0
Views: 527
Reputation: 72
bool has_only_digits(string s){
return s.find_first_not_of( "0123456789" ) == string::npos;}
This method is the simplest way I found to check if a string contains a number. So if it returns true the string has only digits else it contains more than just digits.
If the statement is false you can then clear the cin like you have done above.
Upvotes: 0
Reputation: 11150
Instead of
while(!(cin >> coursework_mark)){
you should use std::getline
std::getline(std::cin, coursework_mark);
https://en.cppreference.com/w/cpp/string/basic_string/getline
Upvotes: 1