Reputation: 13
I'm having a problem where I am wanting to go through an array and check that only positive numbers have been entered. I know that it is possible to use isDigit from ctype.h but I'd rather construct something myself. The way I think it is possible, is to iterate through each element of the array and see if the value stored there is between 0 and 9, but it isn't working. This is my code so far:
char testArray[11] = {'0'};
printf("Enter a string no longer than 10 chars");
scanf("%s", testArray);
int x;
int notanumber = 0;
for (x = 0; x < 11; x++) {
if ((testArray[x] < 0) || (testArray[x] > 9)) {
notanumber++;
}
}
printf("%i", notanumber);
Upvotes: 1
Views: 1418
Reputation: 106012
It is not working because 0
and 9
are integers not characters.
Change your if
condition to
if((testArray[x] >= '0') || (testArray[x] <= '9')){ ... }
to check the digits from 0 to 9.
Upvotes: 1
Reputation: 43518
this line
if((testArray[x] < 0) || (testArray[x] > 9)){
should be replaced by
if((testArray[x] < '0') || (testArray[x] > '9')){
Upvotes: 0