I'm having a problem finding information on the condition statements for loops.
I'm using a do while loop.. and i want it to exit after the user enters 1 or 2. It's being stored into an integer value named "choice."
while(choice < 1 || choice > 2);
I have another lot of code to deal with a letter being entered, but this still takes 1.1-1.9. The compiler treats that range as 1, so it ends up fine in the long run.. but it's bothering me.
Is there a way to basically do that to force the user to select 1 or 2? There is actually not a whole lot of information about multiple conditions out there. All i know is the compiler doesn't care for that too much, and the loop goes infinite even when i choose 1 or 2. I can't tell if its because the compilers knows it should be an integer, or if the tested variable isn't allowed to be in the middle like that above. Any help with explanation would be amazing!
#include <iostream>
#include <string>
usingnamespace std; // standard issue stuff right there.
int main () // I wish I knew how to use functions. Main body
{
int choice ; //variable storing the users decisions
//Story time! using cout and the endl for formatting.
cout << "Ahh yes. That familiar feeling of satisfaction of your grocery choices." << endl;
cout << "As you stand in line, emitting that glorious glow, you realize you've neglected to answer the gorgeous female clerk." << endl;
cout << "She asks if you would like help caring the groceries!" << endl;
cout << endl << endl;
//section for the user to start adventure and to pick a choice.
do {
cout << "Do you allow yourself to be demasculated (1), or do you roll your eyes and let her know you got it (2)?" << endl;
cout << "Don't be stupid, use 1 or 2 for your choice only." << endl;
cin >> choice; //stores users choice into the choice variable
while (cin.fail()) //This is my solution to making the user choose one or two.
{
if (cin.fail()) // if the user has failed at life, this if statement will clear it and ignore their stupidity.
{
cin.clear();
cin.ignore( numeric_limits<streamsize>::max(), '\n'); // This took me forever believe it or not.
}
cout <<"1 or 2 only please! Are you trying to break my program?" << endl;
cin >> choice;
}
}while ( choice < 1 || choice > 2); // I realize this allows 1.0-1.9, but it does not stop the program from running. If the actual value mattered i'd use a different solution.
The copy/paste of code works rather nicely. Was worried for a second.
This does not cause a compiler error, but it does not work. I believe it doesn't work because of the left to right way that the condition is read. This was actually the first thing i've tried. It works if i just use one condition, but not both.
for the record..
while ( choice != 1 || choice !=2 ) does not work either.
while (choice !=1 && choice != 2 ) does not work either.