vendredi 24 décembre 2021

C++ input validation and the input is skipped

void grade::getName(){
    std::cout << "Enter your name: >> ";
    getline(std::cin, name);
    extractLastName();
}

void grade::getInput(){
    std::cout << "\nProfessor " << name << " please enter the grade >> ";
    std::cin >> grade;
    grades.push_back(grade);
    std::cout << "\nAnymore grade? Yes = 1, No = 0 >> ";
    std::cin >> option;
    validation();
}

void grade::medianFun(){
    std::sort(grades.begin(), grades.end()); 
    unsigned short med = grades.size() / 2;
    if((grades.size() % 2) == 0)
        median = ((double)grades.at(med) + (double)grades.at(med-1)) / 2;
    else
        median = grades.at(med);
}
void grade::mean(){
    for(auto i : grades)
        totalGrade += i;
    average = ((double)totalGrade / (double)grades.size());
}

void grade::validation(){
    std::cin.sync();
    while(option != 1 or option != 0){
        std::cout << "Please enter 1 to add more grade, 0 to exit and view the stat " << std::endl;
        std::cin >> option;
        if(option == 1 or option == 0)
            break;
    }
}

void grade::menu(){
    getName();
    do{
        getInput();
    }while(option);
    print();
    std::cout << "\n";
}

int main(){
    grade gradeObj;
    gradeObj.menu();
    return 0;
}

So basically the function validation is causing the problem. Input is skipped, and it will become an infinity loop. I have seen most of the posts are talking about having cin first and get line after, and they use cin.ignore() or cin.sync() to solve the problem. However; those do not work for my situation.

Sample in output

jcmbp:do grading jeffreychan$ g++ -g -Wall -O3 -std=c++11 grading.cpp -o grade && time ./grade
Enter your name: >> J C

Professor C please enter the grade >> 90

Anymore grade? Yes = 1, No = 0 >> 9
Please enter 1 to add more grade, 0 to exit and view the stat 

Professor C please enter the grade >> 
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat 

Professor C please enter the grade >> 
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat 

Professor C please enter the grade >> 
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat 

Professor C please enter the grade >> 
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat 

Professor C please enter the grade >> 
Anymore grade? Yes = 1, No = 0 >> Please enter 1 to add more grade, 0 to exit and view the stat 

Aucun commentaire:

Enregistrer un commentaire