I'm trying to make a program I already made more organized by using functions. the purpose of it is processing a menu with several options for calculating different values. This code is for processing the Main menu, and the error I'm getting is that every character I type comes out as invalid (activates the default case in the switch) even if it is 1, 2 or 3, which are the possible options. What am I doing wrong?
void process_main_menu(){ int c; print_main_menu(); int option=getchar(); while((c=getchar())!='\n' && c!=EOF); switch(option){ case 1: program_state=ST_MENU_BASS; break; case 2: program_state=ST_MENU_TREBLE; break; case 3: program_state=ST_EXIT_PROGRAM; break; default: fprintf(stderr, "%s\n", MSG_INVALID_NUMBER); program_state=ST_MAIN_MENU; } } I'm updating the code as I see it wasn't complete enough. I'm actually using macros for this
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #define OPT_MENU_BASS 1 #define OPT_MENU_TREBLE 2 #define OPT_EXIT_PROGRAM 3 typedef enum { ST_MAIN_MENU, ST_MENU_BASS, ST_MENU_TREBLE, ST_EXIT_PROGRAM, ST_MENU_TREBLE_FREQ, ST_MENU_TREBLE_GAIN, ST_MENU_TREBLE_FREQ_FREQ_TREBLE, ST_MENU_TREBLE_FREQ_RESISTOR_3, ST_MENU_TREBLE_FREQ_CAPACITOR_3, ST_MENU_TREBLE_GAIN_RES5, ST_MENU_BASS_FREQ, ST_MENU_BASS_GAIN, ST_MENU_BASS_FREQ_FREQ_BASS, ST_MENU_BASS_FREQ_RESISTOR_2, ST_MENU_BASS_FREQ_CAPACITOR_1, ST_MENU_BASS_GAIN_RESISTOR_1, } state_t; state_t program_state; void process_main_menu(){ int c; print_main_menu(); char option=getchar(); while((c=getchar())!='\n' && c!=EOF); switch(option){ case OPT_MENU_BASS: program_state=ST_MENU_BASS; break; case OPT_MENU_TREBLE: program_state=ST_MENU_TREBLE; break; case OPT_EXIT_PROGRAM: program_state=ST_EXIT_PROGRAM; break; default: fprintf(stderr, "%s\n", MSG_INVALID_NUMBER); program_state=ST_MAIN_MENU; } }
fprintf(stderr, "Got %d ('%c')\n", option, option);in thedefaultclause and you'd see the information that you typed49 ('1')which would strongly hint at why you have a problem. It takes, perhaps, a bit more experience to know to print both the numeric and character versions of the value inoption, but it becomes automatic over time.case OPT_MENU_BASS:unless you docase (OPT_MENU_BASS + '0'):becauseOPT_MENU_BASSis equal to decimal1not character'1'(which is actually decimal49) or you can doswitch(option - '0')to makeoptiona decimal instead of a character. Look carefully at e.g. ASCII Table.com. Alternatively you could#define OPT_MENU_BASS '1', but the redefinition ofOPT_MENU_BASSwould likely cause issues elsewhere in your code.