I wrote this codes and i wanna ask how come if i enter letters not numbers and it will stuck!!
Also how can i add an error code on the numbers and letters thats if is not 1,2,3,4?
#include <iostream>
#include <cstdlib>
using namespace std;
void menu();
void mainMenu();
void optionsMenu();
void options();
int choice1 = 0;
int choice2 = 3;
int main(int argc, char** argv)
{
menu();
return 0;
}
void menu()
{ do
{
choice2 = 0;
mainMenu();
switch(choice1)
{
case 1:
cout << ">> PLAY Menu Item Selected!\n";
cout << ">> Playing game...\n";
cout << ">> Continuing with program\n";
break;
case 2:
options();
break;
case 3:
break;
}
} while(choice1 != 3);
}
void options(void)
{ do
{
optionsMenu();
switch(choice2)
{
case 1:
cout << "So difficult!\n";
break;
case 2:
cout << "Beep!\n";
break;
case 3:
break;
default: break;
}
}
while(choice2 != 3);
}
void mainMenu(void)
{
cout << "Please select from one of the following options:\n";
cout << "1: Play\n";
cout << "2: Options\n";
cout << "3: Quit\n";
cout << "4: Help\n";
cout << "Enter (1,2,3 or 4 only): ";
cin >> choice1;
}
void optionsMenu(void)
{
cout << "Options Menu\n";
cout << "1 - Difficulty\n";
cout << "2 - Sound";
cout << "3 - Back\n";
cout << "Please choose: ";
cin >> choice2; }
If the program is expecting an integer (a number) but the user enters a letter, then the cin.fail() flag will be set. In order to fix that, you would need to both clear the error flags and empty the input buffer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int choice;
if (!(cin >> choice))
{
cin.clear(); // reset the error flags
cin.ignore(1000, '\n'); // remove up to 1000 characters
// or until newline is found, from input buffer.
}
else
{
switch (choice)
{
case 1:
// etc.
}
}
But, you can avoid the need to worry about that if the input is read as a character instead of an integer.
So is that the way of enter numbers not letters?
But for example it is 1,2,3,4. So if i enter 9.
Should be error.
Also letters too.
i still dont get it mate?
takes character values meaning a-z, 0-9, and symbols.
choosing which one to use is a matter of taste, and how to test if you want numbers only you can always use other functions like isDigit or isAlpha and throw and error if not the one you want.
The program freezes because it does not recognize the input and does not know what to do there on. unless you tell it to ignore what was input like Chervil did at the top, then it will continue as normal.