P.NICHOLAS
P.NICHOLAS

Reputation: 33

Entering a character instead of integer

I'm using a do-while loop to print a menu to the screen. And I'm reading choice as an integer. The proplem is that if the user enter a character the program blows up. How can I avoid that?

#include <stdio.h>
int menu() {            // prints the main menu of labs///
    int choice;
    printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
    scanf("%d", &choice);
    return choice;
}

int main() {
    int choice;

    do {

        choice = menu();
        if (choice != 4) {

            if (choice == 1)
                //lab5(choice);

            else if (choice == 2)
                //lab10(choice);


            else if (choice == 3)
                //  lab11(choice);
            else
                printf("invalid choice\n");
        }

    } while (choice != 4);
    return 0;
}        

Upvotes: 1

Views: 3108

Answers (3)

Adnan Karim
Adnan Karim

Reputation: 11

/*USE This Code*/  
#include <stdio.h>
#include <stdlib.h>
void orderAsk(int orderStorage[1]);
int main()
{     
    int orderStorage[1];
    orderAsk(orderStorage);
    printf("%d",orderStorage[0]);
    return 0;
}

void orderAsk(int orderStorage[1]){
    int d;
    d = scanf("%d", &orderStorage[0]);
    if ( d!= 1) {
        system("cls");
        fflush(stdin);
        printf("Error! Re-Enter\n");
        orderAsk(orderStorage);
    }
}

Upvotes: 0

Gus
Gus

Reputation: 954

The scanf() (and family of functions) returns the number of successful conversions from the input buffer, if the conversion (%d) fails the function returns 0 (or EOF). In this case the character that could not be converted is not removed from buffer, this is why the endless loop occur, the conversion keeps failing for ever.

I used this method to flush the input buffer after the scanf call and the program behaved as expected.

Run the program online (don't know for how long this will stay up)

void flushInput(){
  int c;
  while((c = getchar()) != EOF && c != '\n')
        /* discard */ ;  
}

int menu() {            // prints the main menu of labs///
    int choice;
    printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
    if(scanf("%d", &choice) != 1){
        flushInput();
        return 0;
    }else{
        flushInput();
        return choice;
    }
}

Upvotes: 1

Ryan Fitzpatrick
Ryan Fitzpatrick

Reputation: 783

This should work for you, you need to check the return value of scanf

int menu() {            // prints the main menu of labs///
    int choice;
    printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
    if(scanf("%d", &choice) == 1)
    {
        return choice;
    }
    else
    {
        return 0;
    }
}

Upvotes: 3

Related Questions