My problem is that I'm trying to make a menu as part of my program. There are conditional statements for input, and my else
statement is supposed to say that input is invalid, and wait for input (so as to let the user know they entered something invalid).
This is the relevant snippet, and what I tried:
void main_menu() {
int opt;
system("CLS");
std::cout << "Main Menu" << std::endl;
std::cout << "\n\nWhat would you like to do?" << std::endl;
std::cout << "1) Fight" << std::endl;
std::cout << "2) Store" << std::endl;
std::cout << "3) Exit" << std::endl;
std::cin >> opt;
std::cin.ignore();
if (opt == 1) {
return main_menu();
}
else if (opt == 2) {
return main_menu();
}
else if (opt == 3) {
return;
}
else {
system("CLS");
std::cout << "Invalid!" << std::endl;
std::cin.get(); //error, but not seen in list or console
}
}
int main() {
main_menu();
return 0;
}
What I seem to have screwed up on is the else
. When I run it, the code seemingly passes the std::cin.get()
I've set up.
My desired output:
Input = 1 // valid input
go to statement 1 (empty for time being.)
Input = 6 // invalid, but is handled with the else:
cout << "Invalid!" << ....
//pause
Input = 'a' //invalid, should be like above:
cout << "Invalid!" << ....
//pause // in reality, it passes
I have already tried some methods and looked at some posts in sites other than SO (see post Why is the Console Closing after I've included cin.get()?) (I have tried the cin.ignore()
after cin >> var
method already, not working), but none work.
It does say about newlines and such, but I don't understand about it. Can someone explain how the trailing newlines work, and why is my snippet not working?
EDIT: Other statements of cin.get()
have worked in my actual code.
EDIT: I tried inputting an invalid option other than a number, but it didn't work (say, chars). Nums work though. So the question is now about handling data types other than ints, floats, doubles, etc.