简体   繁体   中英

C - An if-else statement gets stuck and crashes

I have a problem with an code where i have and if-else statement and it needs an input of an integer and otherwise would ask again to enter the number. The code is in a while statement and the problem is that when i enter anything else than an integer the loop gets stuck giving the else statement and crashes

static inline void number_console(void)
{
int x = 0;
fprintf_P(stdout, PSTR(GET_NR_MSG));
lcd_goto(0x40);

if (scanf("%d", &x) == 1 && x >= 0 && x <= 9) {
    printf("\nYou entered number: ");
    fprintf_P(stdout, (PGM_P)pgm_read_word(&numbers[x]));
    fputc('\n', stdout);
    lcd_puts_P((PGM_P)pgm_read_word(&numbers[x]));
    lcd_putc(' ');
} else {
    printf("invalid input\n");
    }
}

Also the code is used in a while statement

while (1) {
    blink_leds();
    number_console();
}

Well, you took care of half of the problems.

You checked for the scanf() failure, that's fine, but when matching fails, the input in the buffer is not consumed, it remains there (waiting for the next occurrence of scanf() to read it).

Thus, the same input (invalid) is fed over and over again. In the else part of the scanf check, you need to clean up the buffer of the invalid input. A very basic way of doing that would be

} else {
    printf("invalid input\n");
    while (getchar() != '\n');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM