#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
cout << "Menu Chooser Program" << endl;
cout << "Difficulty Levels\n\n";
cout << "1 - EASY\n";
cout << "2 - NORMAL\n";
cout << "3 - HARD\n";
int choice;
char again;
do
{
cout << "Your choice\n";
cin >> choice;
switch (choice)
{
case 1:
cout << "You picked EASY\n";
break;
case 2:
cout << "You picked NORMAL\n";
break;
case 3:
cout << "You picked HARD\n";
break;
default:
cout << "Invalid choice!\n";
}
cout << "Run again?\n";
cin >> again;
cout << "Does this code get run?\n";
} while (again == 'y');
srand(time(0)); //seeds random by time
int randomNumber = rand(); //calls the random number
int die = (randomNumber % 6) + 1; //gives you random number between 1 and 6
cout << "You rolled a " << die << endl;
return 0;
}
so here is what happens, whenever you enter in say 6, when you are prompted for choice it goes to the default output, like it should. But when you enter in a char value like say u, it goes to the default, like it should, then leaves the switch statement, like it should but then skips over the following cin, it does not wait for it at all, just goes right over it. Probably just something I am not doing right. Any help would be great.
If you enter something which is not an integer when cin is expecting an int, the fail() flag is set for the cin stream. Any further input will fail until you clear the error flag by doing cin.clear(). It is usually necessary to get rid of the incorrect input by doing cin.ignore() too.
You can simplify this issue if you only need an integer in the range 0 to 9, as these can be handled as a char instead. But if variable choice is changed from type int to type char, the switch-case statements need to reflect this, for example case 1: would need to become case'1':.
I posted a reply but apparently it got deleted... Anyways, thanks for the reply! Very helpful, cleared that up for me. I was pretty sure I was tracing through the code properly. I am use to Java, when something like that happens it just crashes the program ha.