<cctype> isdigit() not producing expected result

Hi;

I'm going through Primer Plus 6th Edition and had an issue with one of the exercises, the question is as follows:

Write a program that reads up to 10 donation values into an array of double. (Or, if you prefer, use an array template object.) The program should terminate input on non-numeric input. It should report the average of the numbers and also report how many numbers in the array are larger than the average.

i was wanting to use isdigit() from the cctype library to test whether the number was a digit by doing:

1
2
3
4
5
6
7
8
9
10
11
12
for (int i = 0; i < 10; i++)
{
	cout << "Donation #" << i + 1 << ": ";
	cin >> donations[i];
	if (!isdigit(int(donations[i])))
	{
		cout << "Non numeric input, end of donations";
		break;
	}
	sum += donations[i];
	++tmp;
}


Which produced the correct output for any number under 100, when the entered value was over 100 it displayed the error message "Non numeric input, end of donations" and ended the loop. I managed to get the program working by using !cin instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Excercise2.cpp

#include <iostream>

int main()
{
	using namespace std;

	cout << "Please enter donation amounts\n";
	double donations[10];
	double sum = 0.0;
	double average;
	int tmp = 0;

	for (int i = 0; i < 10; i++)
	{
		cout << "Donation #" << i + 1 << ": ";
		cin >> donations[i];
		if (!cin)
		{
			cout << "Non numeric input, end of donations";
			break;
		}
		sum += donations[i];
		++tmp;
	}

	average = sum / tmp;
	cout << "The sum of all donations is: " << sum << endl;
	cout << "The average of all donations is: " << average << endl;

	for (int i = 0; i < 10; i++)
	{
		if (donations[i] > average)
			cout << "Donation #" << i + 1 << " is greater than the average\n";
	}

	return 0;
}


Was just wondering if anyone could tell me why using isdigit() behaved like that?
Last edited on
std::isdigit() checks if a character is a decimal digit.

1
2
3
4
5
char d = '7' ;
std::isdigit( c ) ; // yields true

char n = 'a' ;
std::isdigit( n ) ; // yields false 
Topic archived. No new replies allowed.