Home > Mobile >  Input validation of multiple conditions C Program
Input validation of multiple conditions C Program

Time:01-12

I am creating a bank program where the user enters a card number and pin and I am trying to validate their input. It worked for validating one card number and pin but it doesn't work for multiple card numbers and pins.

The code is as follows:

do {
    printf("Card number: ");
    scanf("%d", &cardNum);

    printf("PIN: ");
    scanf("%d", &pin);

    if ( cardNum != 1111 && pin != 2222 || cardNum != 3333 && pin != 4444 ) {
        printf("Error! Card number or PIN is invalid.\n");
    }

} while ( cardNum != 1111 && pin != 2222 || cardNum != 3333 && pin != 4444 );

Any help is appreciated. Thanks!

CodePudding user response:

You're not combining the conditions correctly.

It's generally easier to describe the conditions that you want to match, and then invert the entire thing with a single !(...) around it.

do {
    printf("Card number: ");
    scanf("%d", &cardNum);

    printf("PIN: ");
    scanf("%d", &pin);

    if (!(cardNum == 1111 && pin == 2222 || cardNum == 3333 && pin == 4444)) {
        printf("Error! Card number or PIN is invalid.\n");
    }

} while (!(cardNum == 1111 && pin == 2222 || cardNum == 3333 && pin == 4444));

If you want to rewrite it without the wrapping !(...), see de Morgan's Laws. You'll need to apply it multiple times to each level of condition nesting. The result would be:

if ((cardNum != 1111 || pin != 2222) && (cardNUm != 1111 || pin != 4444))

It's not easy to tell what this is actually trying to match when written like this.

And to avoid writing the condition twice, use a while(1) loop instead of do-while, and break out when the input is valid.

while (1) {
    printf("Card number: ");
    scanf("%d", &cardNum);

    printf("PIN: ");
    scanf("%d", &pin);

    if (cardNum == 1111 && pin == 2222 || cardNum == 3333 && pin == 4444) {
        break;
    }
    printf("Error! Card number or PIN is invalid.\n");
}
  •  Tags:  
  • Related