Program gone haywire when user input is a character

#include <stdio.h>

void calculation(void);
void menu(void);

main()
{
int x = 0;
do
{
printf("Welcome to the Health Club!\n");
printf("Health Club Membership Menu\n");
printf("\t1. Adult Membership\n");
printf("\t2. Senior Citizen Membership\n");
printf("\t3. Exit\n\n");
printf("Please enter your selection : ");
scanf("%d" , &x);
}
while(x != 3);
}

hello the above is the assignment im currently working on. i couldnt stop the program from going haywire if the user input is a character. i am just trying to make a simple program for a health club membership, where users can check the rate of each type of membership and selecting the third option will exit the program. how do i stop user from inputting a character or is there any other way to fix this? thanks in advance!
Something along these lines, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <stdio.h>

void ignore_line() // extract and discard everything in this input line
{
    // keep reading and discarding characters till a new line is read
    char ch ;
    do scanf( "%c", &ch ) ; while( ch != '\n' ) ;
}

int menu()
{
    puts( "Welcome to the Health Club!\n"
          "Health Club Membership Menu\n"
          "----------------------------\n"
          "\t1. Adult Membership\n"
          "\t2. Senior Citizen Membership\n"
          "\t3. Exit\n" );
    printf( "%s", "Please enter your selection 1/2/3 : " );

    int sel ;

    // if an integer is entered and it is one of the valid options, return it
    if( scanf("%d", &sel ) == 1 && sel > 0 && sel < 4 ) return sel ;

    else // other wise, throw this bad input line away and try again
    {
        puts( "input error: try again\n" ) ;
        ignore_line() ;
        return menu() ; // try again
    }
}

int main()
{
    const int sel = menu() ;
    printf( "you selected option #%d\n", sel ) ;
}
Mmmm.

> do scanf( "%c", &ch ) ; while( ch != '\n' ) ;
Doesn't take into account EOF.

> return menu() ; // try again
Use a while loop, or risk blowing the stack with infinite recursion.

Topic archived. No new replies allowed.