alike127
alike127

Reputation: 1

Using switch statements to access functions OOP C++

I've been trying to use switch statements to access different functions in my program and when I compile the code it keeps showing up the default option, regardless of what I input. Am I missing something really obvious here?

All the functions (all voids) are declared in the class. Is this maybe because I am implementing the other 'menu' functions underneath this one?

void bookshop::menu_searchtype() {

std::cout << "Welcome to Hal's Book Emporium!\n\n";

std::cout << "You can search for a book by its:\n";

std::cout << "1. Identification number\n";
std::cout << "2. Title\n";
std::cout << "3. Author\n\n";

std::cout << "Which would you like to use?\n\n";

std::cin >> choice_menu;

int menu_searchtype_no;

switch (menu_searchtype_no) {

    case '1':
        menu_id();
        break;

    case '2':
        menu_title();
        break;

    case '3':
        menu_author();
        break;

    default:
        std::cout << "We seemed to have run into a problem. Please try again\n\n";
        break;
}

}

Upvotes: 0

Views: 827

Answers (2)

SMA
SMA

Reputation: 37043

  • You are reading values into choice_menu and not menu_searchtype_no which you didnt even initialized.
  • Your case statement looks like you are comparing for characters. Remove quotes (if you are reading integers and choice_menu is of integer type) and that should let you move further.

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385244

You never set menu_searchtype_no, so it has an unspecified value. On very rare occasions this may "equal" '1', '2' or '3' (which is 49, 50 or 51 respectively, if you're using ASCII), but far more likely it'll be some random-looking higher value which will trigger the default case.

I guess you meant to write:

switch (choice_menu) {

and

case 1:

etc.

Upvotes: 1

Related Questions