C Looping Number Menu With scanf
A simple number selection menu using scanf()
that loops until the user selects the quit option.
A while
loop using getchar()
is used to clear the stdin
input buffer if an input is submitted that can not be parsed as an int
.
looping_number_menu.c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int doLoop = 1;
while(doLoop){
int userInput = -10;
printf("select: [1]-action one [2]-action two [0]-quit\n");
fflush(stdout);
scanf("%d", &userInput);
switch(userInput){
case 1:
printf("-one-\n");
break;
case 2:
printf("-two-\n");
break;
case 0:
printf("-quit-\n");
doLoop = 0;
break;
default:
printf("Invalid selection, try again.\n");
}
fflush(stdout);
// clear stdin with while loop
while(getchar() != '\n');
}
printf("end.\n");
return EXIT_SUCCESS;
}