-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
  • 807
  • 1
  • 8
  • 11
kelp99
  • 61
  • 1
  • 9
  • 2
    When the user enters "1" they ultimately enter two characters: `'1'` and newline character `'\n'`. The latter is generated by `Enter` key. Your "ERROR" message is the reaction to that `'\n'`. – AnT Jul 25 '18 at 15:47
  • [related](https://stackoverflow.com/q/29658685/2173917)? – Sourav Ghosh Jul 25 '18 at 15:47
  • You also never bother to check if `scanf()` actually reads a character. That will cause all kinds of problems for more complex code. – Andrew Henle Jul 25 '18 at 15:47
  • Please don't post code with line numbers. – Jabberwocky Jul 25 '18 at 15:56
  • @AnT - yes you got it very correct. kelp99 - Also, Please use switch case when you have a long ladder of if else if. Like in this case. – Rizwan Jul 25 '18 at 16:01

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
  • 186,650
  • 20
  • 189
  • 240