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!
#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()
{
constint sel = menu() ;
printf( "you selected option #%d\n", sel ) ;
}