Reputation: 59
This code cannot stop looping even when I enter n or N.
What is causing this?
char next = "";
printf("Do u want continue\n");
scanf("%c", &next);
getchar();
do
{
if (next=='y' ||next=='Y')
{
selection();
}
else
{
printf("invalid Please Enter again");
scanf("%c", &next);
}
} while (next !='n'|| next!='N')
Upvotes: 3
Views: 172
Reputation: 35
while (next !='n' || next!='N') is always true.
You can simply change it like this:
while (next !='n')
Then you input n
, it stopped.
Upvotes: 0
Reputation: 489
Your while conditional will always evaluate to true. The input character will always be either NOT 'N' or NOT 'n'. Because it's only a single character, so it will always not be one of the two. You need you need to instead ensure that it's NEITHER of them. This is a logical AND check, rather than and OR check. So, instead, change that conditional to an AND, a.k.a next !== 'n' && next !== 'N'
, or, if you find using OR makes more sense, the following conditional is equivalent to the AND statement, through use of Boolean logic transformations !(next == 'n' || next == 'N')
.
Cheers!
Upvotes: 2
Reputation: 223699
The conditional (next !='n'|| next!='N')
is always true.
If next
is 'n'
then next!='N'
is true making the whole expression true. Similarly, if next
is 'N'
then next!='n'
is true again making the whole expression true.
What you want here is to use a logical AND &&
:
} while (next !='n' && next!='N')
Upvotes: 4
Reputation: 50778
Besides dbush's answer which is correct:
char next = "";
is wrong, it should be char next;
scanf
but use only getchar
, scanf
is full of pitfalls.Replace this:
char next;
...
scanf("%c", &next);
getchar();
with this:
int next;
...
next = getchar();
Upvotes: 1