I was wondering if anyone could tell me why the following code;
int main ()
{
while((true))
{
int userChoice;
//fprintf(stdout, "Press 1 for Coke.\nPress 2 for Sprite.\nPress 3 for Dr. Pepper.\nPress 4 for Mountain Dew.\nPress 5 for Monster.\nPress 6 for Help.\n\n");
fprintf(stdout, "What would you like? (Press 6 for assistance): ");
std::cin >> userChoice;
if ((userChoice == 1))
{
fprintf(stdout, "\nYou get a Coke and you get a Coke, EVERYONE GETS A COKE!\n\n");
}
else if ((userChoice == 2))
{
fprintf(stdout, "\nDispensing Sprite.\n\n");
}
else if ((userChoice == 3))
{
fprintf(stdout, "\nDropping the Dr. P!\n\n");
}
else if ((userChoice == 4))
{
fprintf(stdout, "\nDo the Dew!\n\n");
}
else if ((userChoice == 5))
{
fprintf(stdout, "\nHere's your Monster, but don't go crazy\n\n");
}
else
{
fprintf(stdout, "\nPress 1 for Coke.\nPress 2 for Sprite.\nPress 3 for Dr. Pepper.\nPress 4 for Mountain Dew.\nPress 5 for Monster.\nPress 6 for Help.\n\n");
}
}
}
causes an infinite loop instead of printing the "else" statement when a non-integer is recieved via std::cin.
I'm assuming it is because userChoice is stored as an integer. How would I prevent this from happening? First guess would be to change it to a string or char but would like a better explanation...
Thank you in advance.
EDIT: From Comments;
Thank you for the answer and input;
The if's instead of switch statements are part of the "Learning". Im brand new, the "beginners challenge" wanted it in if's, then change it to use a switch.
the parentheses, Code::Blocks was throwing compiler warnings so i added them...
using the different printf/scanf etc makes sense.
Maybe more specifically i should ask; why is it that when i input a "6", it properly breaks and returns to the top of the loop but when i input an "a" it repeatedly prints out the else statement as fast as possible