0

I'm currently taking a C/C++ programming class at my school. I am tasked with writing a piece of code that will ask the user how many numbers they would like averaged, then averages them. The program has to contain a for loop. The problem that I am having is that after the user has entered the "n" variable, if they type a character such as "a", the program will immediately spit out an answer as my average. I would like to find a way to prevent the user from entering characters so that my for loop can finish running and average the numbers properly. Here is my code:

{
    int n, i = 1, x = 1;
    double sum = 0, average, value;


    cout << "\nHow many numbers do you want to average?: ";
    cin >> n;

    while (n < 1)
    {
        cout << "\nYou have entered an invalid number.\n";
        cout << "\nHow many numbers do you want to average?: ";
        cin.clear();
        while (cin.get() != '\n');
        cin >> n;
    }

    for (n; i <= n; i++)
    {
        cout << "\nEnter value: ";
        cin >> value;

        sum = sum + value;  

    }

    average = sum / n;

    cout << "\nThe average is: " << average << endl;

    system("pause");

    return 0;

}
Xiaotian Pei
  • 3,210
  • 21
  • 40
Dave
  • 1
  • 1
  • You could put the initial cin in a loop and do a check that the variable is a number. When it resolves as a number, break the loop and continue. – mcraenich Oct 24 '15 at 03:12
  • 1
    Consider looking at solutions proposed in: http://stackoverflow.com/questions/545907/what-is-the-best-way-to-do-input-validation-in-c-with-cin – Dai Oct 24 '15 at 04:03

0 Answers0