2

I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?

#include <iostream>
using namespace std;
int main()
{
    // Get number from user
    int input = 0;
    double accumulator = 0;
    double mean;
    cout << "How many numbers would you like me to average together?\n";
    cin >> input;
    if (input >= 0){ //to check if input is a numerical value

        // Compute and print the mean of the user input

        int number = 1;
        double x;
        while (number <= input) //while corrected
        {
            cout << "Please type a numerical value now: \n";
            cin >> x;
            if (x < 0  || x > 0){ //to check if x is a numerical value
                accumulator = accumulator + x;
            }
            else {
                cout << "Input incorrect"<< endl;
            }
            number = number + 1;
        }
        mean = accumulator / input; // formula corrected
        cout << "The mean of all the input values is: " << mean << endl;
        cout << "The amount of numbers for the average calculation is: " << input << endl;
        }
    else {
        cout << "Input incorrect"<< endl;
    }
    return 0;
}

1 Answers1

0

You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.

while (number <= input) //while corrected
{
    cout << "Please type a numerical value now: \n";
    cin >> x;

    bool error = cin.fail();
    cin.clear();
    cin.ignore(0xFFFF, '\n');

    if (error) 
    { 
        cout << "Input incorrect" << endl;
        continue;
    }

    accumulator = accumulator + x;
    number = number + 1;
}

Alternatively you can initialize x. For example

double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');

if (x == numeric_limits<double>::min())
{ 
    cout << "Input incorrect" << endl;
    continue;
}

If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()

Not related to this issue, but you should also account for divide by zero error.

if (input == 0)
    mean = 0;//avoid divide by zero, print special error message
else
    mean = accumulator / input; 
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77