I have a task named ''Discounted Coffee Machine'' with these conditions:
if(p<a){
printf("\nYour balance is not enough.");
printf("\nRemaining balance: %d",p);
}
else if(p>=a && dis!=dis2){
printf("\nEnjoy your Latte. ");
printf("\nRemaining balance: %d",p-a);
}
else if(p>=a && dis==dis2){
printf("\nThe discount has been applied.\nEnjoy your Latte.");
printf("\nRemaining balance: %f",(float)p-(float)a*0.9);
}
But, if I enter the correct discount code, it doesn't read the second else if. It only reads the first else if. How can I solve this?
I tried with the second else if like only else, but it's not working. I also tried with ',' and '||'.
CodePudding user response:
dis
and dis2
are character arrays
char dis[]="ostim";
char dis2[5];
dis!=dis2
compares the addresses of those 2 different arrays and so dis!=dis2
is always true. Code needs to compare the strings at those addresses. @Chris Dodd
Use strcmp()
which returns 0 when the strings are the same.
Replace dis!=dis2
with strcmp(dis, dis2) != 0
or simply
// else if(p>=a && dis!=dis2){
else if(p>=a && strcmp(dis, dis2)) {
Likewise for else if(p>=a && dis==dis2)
.