0

I am new to C programming and have an assignment to write a Slot Machine programme using structs. I am nearing the end of the code and everything is working fin apart from this one seemingly simple fuction:

float NewCred(){
printf("%s %s %s", sm.fruit1.face, sm.fruit2.face, sm.fruit3.face);
if(sm.fruit1.face == sm.fruit2.face && sm.fruit2.face == sm.fruit3.face){
    printf("\nFULL HOUSE!!! You win %.2f more credits!\n", bet);
    cred += (bet);
}

else if(sm.fruit1.face == sm.fruit2.face || sm.fruit2.face == sm.fruit3.face || sm.fruit1.face == sm.fruit3.face){
    printf("\nHalf House! You win %.2f more credits!\n", bet/2);
    cred += (bet/2);
}

else{
    printf("\nUnlucky! You lose %.2f credits...\n", bet);
    cred -= bet;
}

return cred;
}

The first printf line was just a test to see if the strings for sm.fruit[x].face had been passed into the function, whcih they had. However, no matter what the three values for sm.fruit[x] are, the function always executes the final else statement and I cannot figure out why.

Thank you for any help in advance.

OUTPUT:

ORANGE PEAR ORANGE
Unlucky! You lose 8.00 credits...
You now have 2.00 credits.
KOB
  • 4,084
  • 9
  • 44
  • 88

1 Answers1

3

This is because you cannot use == to compare values of C strings. The proper way of doing it is strcmp.

Instead of this

sm.fruit1.face == sm.fruit2.face

you need to write this:

strcmp(sm.fruit1.face, sm.fruit2.face) == 0

strcmp returns a negative number when the first string is ahead of the second string in lexicographic order, and a positive number when it is behind it. When the two strings are equal, zero is returned. That is the reason behind the == 0 part of the equality check. You can use !strcmp(a, b) as a shortcut as well.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Can't believe this! I've been using strcmp throughout the whole programme and I don't know why it didn't cross my mind here. Thank you! – KOB Feb 13 '15 at 15:46