0

I'm trying to do a check in the input of a menu option field but it produces an infinite loop with no exit not allowing me to insert in the stdin.

MENU

int operationNum;
    printf("Menu\n"
    "1) Create\n"
    "2) Delete\n"
    "3) Show\n"
    "4) Exit\n");

CHECK INPUT

while (1) {
        printf("--> ");
        if ( scanf("%d", &operationNum) )
            break;
}

OUTPUT (I test wrong value)

--> gf
--> --> --> --> --> --> --> --> --> --> --> --> --> --> (...)
luke-uppx
  • 11
  • 1
  • You have not shown the input you give this program. When asking for debugging help, always provide a [mre], including whatever input is necessary to reproduce the problem. – Eric Postpischil Jun 27 '20 at 15:31
  • 1
    `scanf` checks the next character in the input for a match before proceeding. When processing for `%d`, if the next character cannot be a match, say because it is a letter, then `scanf` leaves the character in the input stream and returns. Since there are no matches yet, it returns zero. When your loop calls `scanf` again, it sees the same character in the stream and returns zero again. This continues indefinitely. To make progress, you must read the characters in the stream, thus consuming them and removing them from the stream. Add code to read until, say, a new-line character is read. – Eric Postpischil Jun 27 '20 at 15:33

2 Answers2

0

scanf leaves the \n in the buffer so you need to remove it

while (1) {
        printf("--> ");
        if ( scanf(" %d", &operationNum) )
            break;
        else getchar();
}
0___________
  • 60,014
  • 4
  • 34
  • 74
  • A space before the specifier is useful with `%c`, not with `%d`. Also `else getchar();` consumes only one character, you need to flush until `\n` or `EOF`: `while ((c = getchar()) != '\n' && c != EOF);` – David Ranieri Jun 27 '20 at 22:31
  • @DavidRanieri will work, it will take some more iteration – 0___________ Jun 27 '20 at 22:45
  • Nops, it prints a `--> ` for each non digit, more iterations is not a solution (at least not a clean solution). – David Ranieri Jun 27 '20 at 22:49
-1

This happens because you use scanf(%d, ..) which takes only numbers as input but you are inputing characters, if you want to get input as characters you should use %s instead of %d

Michaelt LoL
  • 452
  • 5
  • 10
  • My idea is to force the user to enter a number, not a character. Scanf returns the number of parameters respected by the format, otherwise it returns 0 which does not allow the exit until the input is valid. – luke-uppx Jun 27 '20 at 15:28
  • 1
    Check this [link](https://stackoverflow.com/questions/26583717/how-to-scanf-only-integer) – Michaelt LoL Jun 27 '20 at 15:32
  • @MichaeltLoL what for in this trivial example? – 0___________ Jun 27 '20 at 15:51