View Full Version : Resolved What is the correct way to write this?
harkly
07-26-2010, 04:10 PM
What is the correct way to write this?
do
{
cout << "Enter your currency type:" << endl;
cout << "A - American" << endl;
cout << "P - Pesos" << endl;
cin >> currencyType;
} while (currencyType = (toupper(currencyType) != 'A' || currencyType = (toupper(currencyType) != 'P' )));
I get this error but am not sure what the correct syntax should be
error C2106: '=' : left operand must be l-value
tomws
07-26-2010, 04:46 PM
You're using the assignment operator (=) when you should be testing for equality (==).
harkly
07-26-2010, 04:59 PM
If I convert the input to upper case and then compare I still can only get it to work when comparing only 1 item
do
{
cout << "Enter your currency type:" << endl;
cout << "A - American" << endl;
cout << "P - Pesos" << endl;
cin >> currencyType;
currencyType = toupper(currencyType);
cout << currencyType << endl;
} while (currencyType != 'A');
I need to compare to 2 items, so the choice has to be A or P and if niether repeat the options
} while (currencyType != 'A' || currencyType != 'P');
how is that done?
tomws
07-26-2010, 05:11 PM
You're confusing ANDs and ORs. When an OR is used, the first condition that evaluates to true restarts the loop. So, consider the logic...
User chooses 'X'.
Type != 'A'? True, so loop.
User chooses 'P'.
Type != 'A'? True, so loop.
An AND requires both statements to be true. Here's the example above with an AND instead of an OR:
User chooses 'X'.
Type != 'A'? True, so check next.
Type != 'P'? True. True AND true evals to true. So, loop.
User chooses 'P'.
Type != 'A'? True, so check next.
Type != 'P'? False. True AND false evals to false. So, exit loop.
When I was learning these in school and getting confused, I'd draw a truth table. That helped to understand where the actual results were coming from.
EDIT: I may be wrong on the early exit for conditional testing. That may depend upon language implementation. Not sure. Even if I'm wrong on that, I think the logic in the first case above is still flawed. Here is the case where both are tested (no early exit):
User chooses 'X'.
Type != 'A'? True. Check next.
Type != 'P'? True. True OR true evals to true. So, loop.
User chooses 'P'.
Type != 'A'? True. Check next.
Type != 'P'? False. True OR false evals to true. So, loop.
harkly
07-26-2010, 07:22 PM
Thanks!
I was able to get it with that info
} while ((currencyType != 'A') && (currencyType != 'P'));
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.