C ++用户输入验证无法正常工作

时间:2019-10-08 10:15:14

标签: c++ validation

我有这段代码要求输入数字并将其存储在变量中。我正在尝试对输入进行验证,但是它表现得很奇怪。

#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;
    }


}

如果用户输入“ 45kuefggf”,则将数字45存储为课程标记,并且代码按提示cout <<“超出范围,请输入有效的考试标记:”;。我不知道为什么要这样做,如何使它检查用户是否输入了有效的数据类型?

2 个答案:

答案 0 :(得分:1)

代替

Python

您应该使用while(!(cin >> coursework_mark)){

std::getline

https://en.cppreference.com/w/cpp/string/basic_string/getline

答案 1 :(得分:0)

bool has_only_digits(string s){
return s.find_first_not_of( "0123456789" ) == string::npos;}

此方法是我发现检查字符串是否包含数字的最简单方法。因此,如果返回true,则该字符串仅包含数字,否则包含的位数将不止于此。

如果该语句为假,则可以像上面一样清除cin。