-1

I'm starting to write code for a small bank account program, but my if/else statements aren't working. At the top of the loop, I use scanf to get user input about which option needs to be executed next. The first one always works, but after that, the error statements always get printed.

For example, the user types 1. What gets printed is:

case 1
ERROR, please try again

Only case 1 should be printing, why is the Error message printing too? I tried using switch case statements but that didn't work either.


Here's my code:

char num = '7';
while (1) {
    if(num == '7') {  
        printf("0. Exit\n1. Deposit\n2. Withdrawal\n3. Add account\n");
        printf("4. Remove account\n5. Balance inquiry\n6. View accounts\n");
        printf("Enter option: (0/1/2/3/4/5/6)\n");
        scanf("%c", &num);
    }
    else if (num == '0') {
        exit(0);
    }
    else if (num == '1') {
        printf("case 1\n");
        num = '7';
    }
    else if (num == '2') {
        printf("case 2\n");
        num = '7';
    }
    else if (num == '3') {
        printf("case 3\n");
        num = '7';
    }
    else if (num == '4') {
        printf("case 4\n");
        num = '7';
    }
    else if (num == '5') {
        printf("case 5\n");
        num = '7';
    }
    else if (num == '6') {
        printf("case 6\n");
        num = '7';
    }
    else {
        printf("ERROR, please try again\n");
        num = '7';
    } 
}
Student
  • 805
  • 1
  • 8
  • 11
kelp99
  • 71
  • 2
  • 9

1 Answers1

5

The %c format specifier to scanf accepts any single character, including a space or newline.

If for example the user inputs "1", they are actually sending the character "1" and a newline character. The "1" character is read of the first iteration of the loop and the newline stays in the input buffer. On the next iteration, scanf immediately reads the newline in the buffer. And because the character code for a newline doesn't match any of your if cases, it falls through to the else.

Change the scanf call to add a leading space. That will consume any whitespace:

scanf(" %c", &num);
dbush
  • 205,898
  • 23
  • 218
  • 273