Why does this particular cin.get() statement not work in C++ when I input a char? -


my problem i'm trying make menu part of program. there conditional statements input, , else statement supposed input invalid, , wait input (so let user know entered invalid).

this relevant snippet, , tried:

void main_menu() {     int opt;     system("cls");     std::cout << "main menu" << std::endl;     std::cout << "\n\nwhat 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, not seen in list or console     } } int main() {     main_menu();     return 0; } 

what seem have screwed on else. when run it, code seemingly passes std::cin.get() i've set up.

my desired output:

input = 1 // valid input go statement 1 (empty time being.)  input = 6 // invalid, handled else: cout << "invalid!" << .... //pause  input = 'a' //invalid, should above: cout << "invalid!" << .... //pause // in reality, passes 

i have tried methods , looked @ posts in sites other (see post why console closing after i've included cin.get()?) (i have tried cin.ignore() after cin >> var method already, not working), none work.

it newlines , such, don't understand it. can explain how trailing newlines work, , why snippet not working?

edit: other statements of cin.get() have worked in actual code.

edit: tried inputting invalid option other number, didn't work (say, chars). nums work though. question handling data types other ints, floats, doubles, etc.

by default, ingore ignore 1 character. there @ least 2 characters after input in windows \r , \n.

you better do:

cin.ignore(999,'\n') 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -