Andibadia
Andibadia

Reputation: 31

getchar returns a different character

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;     
}
}

Upvotes: 2

Views: 88

Answers (1)

dbush
dbush

Reputation: 223739

You're reading in a character such as , which is stored as its ASCII code, not a numerical value.

You need to change your cases to look for the character '1', not the number 1.

    case '1':
        program_state=ST_MENU_BASS;
        break;
    case '2':
        program_state=ST_MENU_TREBLE;
        break;
    case '3':
        program_state=ST_EXIT_PROGRAM;
        break;  

EDIT:

Given the macros you're using, you need to modify the macros to represent the characters '1', '2' or '3' instead of the numbers 1, 2 or 3.

#define OPT_MENU_BASS '1'
#define OPT_MENU_TREBLE '2'
#define OPT_EXIT_PROGRAM '3'

Upvotes: 4

Related Questions