Hi all. I'm having a minor problem with cases in my program. If I enter a number that is out of my case range (say I enter a 10 when there are only 4 cases) I've got my default to output an error prompt. When I enter a character, say 'F', the program loops forever. How do I fix this?
void usersChoice(int ans)
int counter2 = 1;
switch (choice)//roll thru options
case 1: //if they picked the number 1, its gonna go to this function,
//thats pretty much how the whole thing works
unsigned int counter;
searchInput = "";
cout << "\n\n\t\tWhich item would you like to check the inventory for?\n\n";
for (counter = 0; counter < itemName.size(); counter++)
cout << "\t\t\t" << counter + 1 << ". " << itemName[counter] << "\n";
cout << "\n\n\t\t\t Choice: ";
cin >> searchName;
//cout << "\n\n\t" << itemName[searchName - 1];
//input = ;
searchInventory(itemName[searchName - 1]);
// run sellStock function
// run print Report
// exit the program
default://THEY'RE NOT FOLLOWING DIRECTIONS?!?!
cout << "Invalid Input"
<< endl;//if directions aren't followed
I took your program and cleaned it up to where all it was is a simple switch statement. There are multiple ways you can fix your problem, the easiest of which would be to change the variable that goes through the switch statement (in your code, its the variable 'choice')
from an integer to a charecter ( char choice; ). This will allow it to cach when they type in stuff like 'f' or 'flakdjljrlkjdaklr', and give them the invalid error. Heres a sample:
Notice the change from case 1: to case '1': . This makes it so that it looks for '1' the charecter, not 1 the integer, thus making it go to the default case when an invalid charecter is typed, such as 'a'. NOTE: when it is charecter '1', you can not take '1' - 2 and get -1. This is because '1' is no longer a "counting number", its simply a charecter on the screen, such as a, b, c, d, e, etc. is.