void showArray(const int arr[], int size)
{
cout << " Scores in ascending order." << endl;
for (int count = 0; count < size; count++)
{
cout << " " << arr[count] << "";
}
cout << endl;
cout << endl;
}
// function to get average of the array
void average(int testScores[], int numGrades)
{
float total = 0.0;
for (int count = 0; count < numGrades; count++)
{
total += testScores[count];
}
float average = total / numGrades;
cout << " This is the average of the scores entered." << endl;
cout << endl;
cout << fixed << showpoint << setprecision(2);
cout << " *** " << average << " ***" << endl;
}
This program was made to allow students to enter as many test scores as they want and the program will show them in ascending order and then will calculate the average of all test scores. It works wonderful until you enter a negative test score and then it throws the averaging process off. I can't seem to be able to make the program not accept the negative numbers. Any clues or hints would work wonders! Please and Thank You.
The latest version of the standard cleared up a little confusion among compilers about that issue -- used to be the GCC would put the stream in error state if you tried to enter a negative when an unsigned was expected, but the standard now clearly mandates that if it is possible to represent it then it must.
Just like unsigned max = -1;, if you try to input a negative number then it will convert it to an unsigned value.
In any case, the only way to conclusively deal with negative inputs is to check to see if it begins with a '-' or not. (Sadly.)
The cleanest way is to write a function to do it, either a la std::getline() or as an input manipulator. Here's the former:
1 2
#include <cctype>
#include <iostream>
1 2 3 4 5 6 7 8 9 10
double input_no_negatives( std::istream& ins )
{
double result = 0;
ins >> std::ws; // skip all whitespace
if (!std::isdigit( ins.peek() ))
ins.setstate( std::ios::failbit );
else
ins >> value;
return result;
}