0

I am trying to creating a console program with menu in c. But I have a problem about validating the option int value. When I put char value it accepts it. I am trying to catch this condition. It understands the condition but scanf is not working second time to read input. It just skips. My code below. Thanks for help!

while (true) {

    printf("%s", "Choose one option: ");

    while (scanf("%d", &choice) != 0) {
        puts("This is not a number! Enter again:");
    }

    // checking input 
    while (choice < 1 || choice > 8){
        puts("Wrong input! You can choose only 1 - 8!");
        printf("%s", "Choose one option: ");
        scanf("%d", &choice);
    }

    if (choice == 8)
        break;

    (*options[choice])();
}
  • 2
    `scanf("%d", &choice) != 0` is true when `scanf` successfully reads an `int`. You want `!= 1`. Also, you need better code to handle when the user enters something that is not a number—`scanf` with `%d` will stop at a character that is not part of a number, and that character will remain in the stream, which will prevent any later `scanf` with `%d` from working. You need to remove the character from the stream (by reading it). – Eric Postpischil May 10 '19 at 00:32
  • @Eric That looks like an anwer in a comment. – Yunnosch May 10 '19 at 05:24
  • First of all thank you for your answers. But actually, I couldn't understand well. My problem is that scanf is not waiting for new input when it gets a string or char. I can catch whether an input is a int or not but scanf is not read (or wait ) for new input. –  May 10 '19 at 09:07
  • Thanks for answers again I found a solution from another stackoverflow question. The link who want to visit https://stackoverflow.com/questions/17827603/scanf-wont-execute-for-second-time?lq=1 Grijesh Chauhan's code worked for me –  May 10 '19 at 09:36

0 Answers0