What's wrong in the below code?
I am stuck in the do while loop. Am I comparing character wrong? I tried using scanf("%c", &answer); as well but same result
char answer[10];
for (i = 0; i < wish; i )
{
/* ... */
/* ... */
do
{
printf(" Does this item have financing options? [y/n]:");
scanf("%s", &answer[i]);
if ((answer[i] != 'y' )|| (answer[i] != 'n'))
{
printf("\nERROR: Must be a lowercase 'y' or 'n'");
}
} while ((answer[i] != 'y') || (answer[i] != 'n'));
Thank you in advance!
CodePudding user response:
You are stuck in your loop because your condition for continuing the loop is always true.
If you have trouble seeing that try to name a letter which is neither different to "y" nor different to "n".
Take for example "a", it is different to both.
Take for example "n", it is not different to "n", but it IS different to "y".
Take for example "y", it is different to "n", though not different to "y".
So whatever letter comes in, the loop will continue.
To solve, use the comment by Chris and change to
((answer[i] != 'y' ) && (answer[i] != 'n'))
This way, any other letter than "n" or "y" will be either different than "n" AND different than "y" and will continue the loop, while both "y" and "n" will be different from at least one of the two and end the loop.
Once you got the condition right it might only be necessary once, i.e. only in the loop. The additional if
is unneeded, at least in the shown code. You might have code which needs it, outside of what you show here.
CodePudding user response:
Building on @Yunnosch's excellent answer, there us another way of looking at the logic of checking to see if something is not a set of characters.
We can look at it as checking to see if a character is not 'y'
and not 'n'
:
answer[i] != 'y' && answer[i] != 'n'
Or... we can check to see if it is either 'y'
or 'n'
:
answer[i] == 'y' || answer[i] == 'n'
Then simply negate that!
!(answer[i] == 'y' || answer[i] == 'n')
Another alternative
One more way of looking at this, because char
is a numeric type, would be to use a switch.
switch (answer[i]) {
case 'y':
case 'n':
/* Do whatever happens when there is a valid input */
break;
default:
printf("\nERROR: Must be a lowercase 'y' or 'n'");
}
The only real advantage of using switch here is that it makes checking for things like capital y and n very easy:
switch (answer[i]) {
case 'y': case 'Y':
case 'n': case 'N':
/* Do whatever happens when there is a valid input */
break;
default:
printf("\nERROR: Must be a lowercase 'y' or 'n'");
}