ok well I'm using a switch statement for variable "choice"...
I want to either:
1) check that the value choice is >=0 and <=5... if not display "Invalid input" and if correct, return(choice)
OR
2) change variable choice to string, and do a stringcompare, to check if choice = 0, if it is close the program (return(0)), if not follow that by a switch statement
switch (choice)
{
case 0: ...
case 1: ...
case 2: ...
case 3: ...
case 4: ...
case 5: ...
default: cout << "Hey foo! Choose properly!\n";
}
There is, however, a design error in your code. First is the name of your function: "displayMenu". The function does more than simply display the menu -- it also gets user input. You might want to name your function more appropriately.
The second is using the int reference as an argument. Why are you doing that? Just return the proper value from the function.
A proper exit condition of the function might very well be to only return a valid choice.
int menu(string id, string name)
{
int choice;
// This part displays the menu
clrscr();
cout << "Book Price (ID: " << id << " Name: " << name << ") ver 1.0\n\n";
cout << "MAIN MENU\n";
...
cout << setfill('_') << setw(53) << "_" << "\n\n";
// This part gets a valid user input
while (true)
{
cout << "Your choice --> ";
cin >> choice;
// if choice was valid, we're done
if (cin && (choice >= 0) && (choice <= 5))
break;
// if choice was invalid (or something worse), we need to try again
if (!cin)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "You must choose in 0 through 5.\n";
}
return choice;
}
After this, your calling code only needs to know that a valid choice is always returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
bool done = false;
while (!done)
{
switch (menu("12345", "Gulliver's Travels"))
{
case 0: done = true; break;
case 1: add_book(); break;
case 2: find_book(...); break;
case 3: list_all_books(); break;
case 4: delete_book(); break;
case 5: update_book(...);
}
}
return 0;
}
I really don't know how your program is structured, so the main() program example I gave there will obviously need some adjustment...