Categories
Mastering Development

How to get an integer from the user and loop if they enter anything else other than an Integer – C89

So I have a bit of code like this.
Just a note this is in C89.

void inputChoice(int* choicePtr)
{
    int choice;
    printf(BLUE "\nINPUT: " RESET);                     /* Print input using the ansi colour code for Blue. */
    scanf("%d", &choice);                               /* Parse the choice. */

    while ((choice < 1) && (choice > 5))                /* Loop until choice is one of the menu options. */
    {
        /* Request for a valid menu option, printing this using the ansi colour code for Red, then resetting back to the default colour. */
        printf(RED "\nMenu Selection must be between (1 and 5) inclusive. \nPlease Re-enter. \n" RESET);
        scanf("%d", &choice);                           /* Parse the choice. */
    }
    *choicePtr = choice;                                /* Set the choice pointer to the valid choice after validation. */
}

Which gets the choice. It works fine for integers. But if someone enters anything else, for example a Character. It infinitely loops.
I want to somehow check for if a character is entered.

One way I tried this was by adding this to check if a character was entered since the integer would be 0 if it didn’t scan properly.

Like this:

scanf("%d", &choice);

while (choice == 0)
{
    printf("Invalid Choice Re-enter.");
    scanf("%d", &choice);
}

But that doesn’t work either.

Any help would be great thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *