0

How do I put an error message to this? like for example: you accidentally pressed a letter intead of a number in grades then an error message will show #include using namespace std;

int main()
{
        double assignment1, assignment2, seatwork1, seatwork2, quiz1, quiz2, majorexam, grade, major, assignment, seatwork, quiz;
        string name;

        cout<<"Enter Student name: ";
        cin>>name;
        
        cout<<"Enter grade for assignment 1: ";
        cin>>assignment1;
        cout<<"Enter grade for assignment 2: ";
        cin>>assignment2;
        cout<<"\nEnter grade for seatwork 1: ";
        cin>>seatwork1;
        cout<<"Enter grade for seatwork 2: ";
        cin>>seatwork2;
        cout<<"\nEnter grade for quiz 1: ";
        cin>>quiz1;
        cout<<"Enter grade for quiz 2: ";
        cin>>quiz2;
        cout<<"\nEnter grade for major exam: ";
        cin>>majorexam;
       
        
        float aveAssignment=(assignment1+assignment2)/2;
        assignment = (aveAssignment)*.1;
        float aveSeatwork=(seatwork1+seatwork2)/2;
        seatwork = (aveSeatwork)*.2;
        float aveQuiz=(quiz1+quiz2)/2;
        quiz = (aveQuiz)*.3;
        major = majorexam*.4;
        grade = (assignment+seatwork+quiz+major);
        cout<<"Final Grade is: "<<grade;
        return 0;
} 
  • The linked question applies to integers, but the same thing works for doubles as well, with slight adjustments. – Sam Varshavchik Mar 27 '21 at 12:54
  • I think a simple way would be to take input as a string, try `std::stod` and catch any exception thrown, and then handle the exception. – mediocrevegetable1 Mar 27 '21 at 12:59
  • @SamVarshavchik I think [this](https://stackoverflow.com/questions/16934183/integer-validation-for-input) or [this](https://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c) will be better, because they work for floating point numbers with almost no modification (except for replacing `int` with `float`). – Lukas-T Mar 27 '21 at 13:00

0 Answers0