i try to do a simple menu using switch. I also want to do a check if the user made a valid input (Only int from 1 to 4). Entering -4 or 44 is working fine with this check. B
Read into a string and try to convert to int:
#include <sstream>
#include <string>
using namespace std;
int menu() {
int enter;
string str;
bool exit = false;
do {
cout << "Wie soll angefangen werden: " << endl; //Enter your choice
cout << "1 - Spiel starten" << endl; // do game();
cout << "2 - Highscore " << endl; //do score();
cout << "3 - Quiz starten " << endl; //do quiz();
cout << "4 - Ende " << endl; //end the programm
cin >> str;
istringstream buffer(str);
buffer >> enter;
switch (enter) {
case 1:
game();
break;
case 2:
score();
break;
case 3:
showQuizDialog();
break;
case 4:
exit = true;
break;
default:
cout << "Keine gültige Eingabe, nochmal: " << endl; //invalid input, again
void flushCin();
} //end of switch
} while (exit == false);
return enter;
}//end of menu();
If entering other things than numbers into an int value directly this might not fit into the reserved space of an int and can result in funny behaviour. So just read into a string first and then interpret it.
It's because the input is trying to get an integer. When the input is not an integer, the input is left in the buffer, so next time around in the loop the same input is still there.
Also, you are not calling the flushCin
function in the default case, you are declaring it. You might want to remove the void
keyword. I guess it does the correct thing? (I.e. calling std::cin.ignore() and std::cin::clear().)