Menu options

Hey guys! Kind of a basic question but I cant get it right. Im using a do while loop to run a series of menu options. The options go through 1,2,3,4 and 0. The while condition to keep the loop running is when the choice variable for the menu is not equal to 0. When 0 is entered the program ends. This all works smoothly. I need to add something that makes it so that if something other than 1,2,3,4,0 is entered I get an invalid choice error and the loop continues running. I tried doing an if statement like this :

if(choice != 1||2||3||4){
cout << "Invalid option. Try again" << endl;
}

This sort of worked but it gave me some issues and wasn't smooth. What code do I need to put in place in the loop to give me this invalid option message consistently.


Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int get_choice()
{
    std::cout << "enter choice (0,1,2,3, or 4): " ;

    char choice ;
    std::cin >> choice ;

    // note that '3' - '0' == 3 etc.
    if( choice >= '0' && choice <= '4' ) return choice - '0' ;

    std::cout << "invalid choice. try again\n" ;
    return get_choice() ; // try again
}

int main()
{
    const int choice = get_choice() ;
    std::cout << "your choice is " << choice << '\n' ;
}
Ah. I dont know why I didn't think to use greater than and less than in the mix. I appreciate your time thank you!
you could use the boost::program_options library. It is easy to use, robust and well documented.
https://theboostcpplibraries.com/boost.program_options
Registered users can post here. Sign in or register to post.