I am writing a currency converter in C.
I sat my loop to keep looping while the the user doesn't hit 'Q'
or 'q'
.
but it doesn't exit the loop if I use two conditions, only one condition is executed
Here is my code
do
{
.... some code....
// then I ask user for option
scanf("%c", &option);
switch (option)
{
case 'U':
case 'u':
printf("Enter the amount in SAR: ");
scanf("%f", &amount);
printf("\n%.3f SAR => %.3f USD", amount, amount * 0.266667);
break;
case 'E':
case 'e':
printf("Enter the amount in SAR: ");
scanf("%f", &amount);
printf("\n%.3f SAR => %.3f EURO", amount, amount * 0.273187);
break;
case 'q':
case 'Q':
break;
}
} while((option) != 'q' || 'Q');
CodePudding user response:
The expression while((option) != 'q' || 'Q')
will always be true because 'Q' is a value that is not zero (false).
You probably meant while(option != 'q' && option != 'Q')
Since Q/q is means the user wants out:
case 'q':
case 'Q':
option = 'q';
break;
}
} while( option != 'q' );
CodePudding user response:
You cannot use logical operators on strings. You have to combine booleans. In this case you need the AND operator, because both conditions have to be true to continue the loop.
...
} while(option != 'q' && option != 'Q')