rus64
rus64

Reputation: 47

C: Checking an array contains only numbers in the range 0-7

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

Answers (5)

Vikram Singh
Vikram Singh

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

haccks
haccks

Reputation: 106012

Try this

if(array[i] >= 0 && array[i] < 8 ) {...}  

No need to check for isdigit as it works for chars not for ints or float.

Upvotes: 1

xtof pernod
xtof pernod

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

CodyAntcliffe
CodyAntcliffe

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

Phil Perry
Phil Perry

Reputation: 2130

  1. It's probably the scanf() function barfing on non-integer input. The error message should give some hint if that's the case.
  2. You've read the input as a number already, so isdigit() is likely going to be false (0). It expects a single character input.
  3. for(int i looks more like C++ than C. Your compiler might be actually compiling in C++ mode.
  4. Note that if you enter an unsigned integer starting with a 0 and containing only the digits 0 through 7, that C is likely to interpret that as an octal number. If you enter something like 01234 it may well be read in as something other than decimal 1234.

Upvotes: 0

Related Questions