So I'm not interested in how to fix this, but rather I want to know why it does what it does. When you give it a letter (instead of an integer that it wants) it causes the menu to display over and over and over... (I know repeat is set to yes) - why doesn't it wait for another cin>>choice though?
#include <iostream>
usingnamespace std;
char orderNumber (int);
int menu ();
int main ()
{
while(orderNumber(menu()) == 'y'); //run until told to stop by user.
return 0;
}
int menu ()
{
int choice;
cout << endl;
cout << "============= M E N U ===============" << endl << endl;
cout << "Please select from one of the following:" << endl;
cout << "8. Redisplay menu." << endl;
cout << "9. Quit." << endl;
cin >> choice;
return choice;
}
char orderNumber (int choice)
{
char repeat = 'y';
switch (choice)
{
case (8):
break;
case (9):
cout << endl << "Goodbye!" << endl;
repeat = 'n';
break;
default:
cout << "Not a valid selection, please try again." << endl;
break;
}
return repeat;
}
Again my question is not how to do it differently - I could create more robust user entry code and error checking or what have you. I want to know why it goes into an endless loop without waiting for the next cin >> choice (line 24) every time it loops.
When you read in something that is not of the type you told it it would be, the input stream can become corrupted. Once this happens, any reading from it will likely fail. This is why subsequent reads typically fail/skip, and your loop loops forever (conceivably).
Exactly what it is that causes the corruption has to do with the format in which data is stored in a computer. It expects a certain format and is given another, but has no choice but to try and store it as the former pattern - which will probably fail.
Any recommended reading for that kind of knowledge?
Most of the teach yourself books are heavy on the "here's an example of how you use the object/operator/etc" but pretty light on the background knowledge and behind-the-scenes, indepth workings. I am left experimenting with snippets and trying to derive the inner mechanisms based on mistakes I make as I go along or inspirations I have for trying other ways to do it. Don't get me wrong, that stuff is fun, but it is an inefficient and spotty way to gain insight.