Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Below is my code and the program works fine until I enter anything other than a number. The problem occurs during the input validation of score.
C++
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int counter = 0;
    double score,
           averagescore,
           totalscore = 0.0;

    cout << "Enter the score of a student, or -1 if no more students are left.\n";
    cin >> score;
    while (score < -1 || score > 100)
    {
        cout << "\nThat is not a valid answer please enter a percent between -1 and 100\n";
        cin >> score;
    }

    while (score != -1)
    {
        totalscore += score;
        cout << "\nEnter the score of a student, or -1 if no more students are left.\n";
        cin >> score;
        while (score < -1 || score > 100)
        {
            cout << "\nThat is not a valid answer please enter a percent between -1 and 100\n";
            cin >> score;
        }
        counter++;
    }

    averagescore = totalscore / counter;
    cout << "\nThe average score of the class is: " << averagescore << '%' << endl;
}


What I have tried:

I tried looking through to see if there were any logic errors and none came to me even though I looked through several times. I'm assuming this is a logic error, but I am not sure what I should do to make it so this input validation only accepts numbers between -1 and 100.
Posted
Updated 18-Sep-18 20:10pm
v2

1 solution

See here: Lecture Notes - cin.fail(), cin.clear(), cin.eof() and strchr()[^] - use cin.fail to check if the user entered a valid number at all, or the word "Hello" for example.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900