Reputation: 47
I'm having difficulty ensuring an array is filled with only numbers in the range 0-7. When I fill the array with numbers outside the range eg. 0 0 0 8 the error message displays. However if the user enters a letter my program crashes.
int array[4] = {0};
scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]);
for(int i=0; i<4; i++)
{
if(isdigit(array[i]) && array[i]<8 && array[i]>=0)
{
// continue program
}
else
{
printf("Invalid entry.");
break;
}
}
Any help would be greatly appreciated.
Upvotes: 0
Views: 3028
Reputation: 958
The issue is that the isdigit() is used for testing whether a character is a digit and takes character typecasted into integer as an argument and you are passing an integer. When you pass it an integer 0 it is actually 0 in decimal but when you pass it character '0' it is 48 in decimal.Since '0' in ascii is 48 in decimal, so to convert from ascii to integer just subtract 48 from the input character before testing it for range (between 0 and 8)
char array[4] = {0};
int i=0;
scanf("%c %c %c %c", &array[0], &array[1], &array[2], &array[3]);
for(i=0; i<4; i++)
{
if(isdigit(array[i]) && (array[i]-48) <= 7 && (array[i]-48) >= 0)
{
printf(" continue program");
}
else
{
printf("Invalid entry.");
break;
}
}
return(0);
}
Upvotes: 2
Reputation: 106012
Try this
if(array[i] >= 0 && array[i] < 8 ) {...}
No need to check for isdigit
as it works for char
s not for int
s or float
.
Upvotes: 1
Reputation: 883
One less test (than haccks' solution):
if (array[i] & ~7) {
invalid_input();
} else {
/* valid input */
}
If you still have problems, then the problem may lie elsewhere ?..
Upvotes: 2
Reputation: 59
You can just search the elements in the array and verify that they are between 0 and 7.
if(array[i]>=0 &&array[i]<=7)
{
continue program
}
else
. . .
Upvotes: 0
Reputation: 2130
for(int i
looks more like C++ than C. Your compiler might be
actually compiling in C++ mode.01234
it may well be read in as something other than decimal 1234.Upvotes: 0