Home > front end >  It is possible to do a comparation between array[i] and a number?
It is possible to do a comparation between array[i] and a number?

Time:11-25

I've done this procedure but the program only asks one time the Input credit card digit group #%d, when I put that it has to do it 4 times. So I guess the problem is the comparison array[i] > 999 && array[i] < 9999 how can I change it so it works?

void demanarDigits(int i, int array[MAX]) {
    for (i = 0; i < 4; i  ) {
        printf("Input credit card digit group #%d: ", i   1);
        scanf("%d", &array[i]);
        if (array[i] > 999 && array[i] < 9999) {
            i = i   1;
        }
        while (array[i] > 9999 || array[i] < 1000) {
            printf("ERROR: Digit groups must have 4 digits\n\n");
            printf("Input credit card digit group #%d: ", i   1);
            scanf("%d", &array[i]);
            if (array[i] > 999 && array[i] < 9999) {
                i = i   1;
            }
        }
    }
}

CodePudding user response:

I think you have to put the array argument of the function like this:

void demanarDigits(int i, int array[])

You mustn't put the index.

CodePudding user response:

At least this problem

Off-by-1.

To test a 4 digit number in th [1000-9999] range, I'd expect

// if (array[i] > 999 && array[i] < 9999) {
if (array[i] > 999 && array[i] <= 9999) {
// or better as 
if (array[i] >= 1000 && array[i] < 10000) {

To test for a 4 digit input in the range [0-9999], use "%n" to record scanning offset.

// scanf("%d", &array[i]);
int start, end;
if (scanf(" %n%d%n", &start, &array[i], &end) == 1) {
  if (end - start == 4 && d >= 0) Good();

Still, I think using fgets() to read the input line and convert it to a string is best.

char buf[100];
if (fgets(buf, sizeof buf, stdin)) }{
  // Now parse buf[]

CodePudding user response:

Hello I think this will work for you.

#include<stdio.h>

int demanarDigits (int array)
{
    if (array > 9999 || array < 1000)
    {
        printf("ERROR: Digit groups must have 4 digits\n");
        return 0;
    }
    else
        return 1;
}

int main ()
{
    int array[4],a;
    for (int i=0; i<4; i  )
    {
        printf ("Input credit card digit group #%d: \n", i   1);
        scanf ("%d",& array[i]);
        a= demanarDigits (array[i]);
        if (a==0)
            i--;
    }
    return 0;
}
  •  Tags:  
  • c
  • Related