Search code examples
cif-statementswitch-statementplaying-cards

C Program Switch and If statement


So i am trying to create a C code program that will be given the shorthand notation for a playing card and will determine the formatted playing card. Example Input: H 8 Output: 8 of Hearts

    Input: C 14
    Output: Ace of Clubs

Rank: 2-10, 11 Jack, 12 Queen, 13 King, 14 Ace Suit: C Clubs, D Diamonds, H Hearts, S Spades But in the final stages of implementation i ran into a couple serious problems. The program runs fine when I enter like D 5 but enter D 12 will make it list queen then jack then 12 of diamonds.

Heres the code: http://pastebin.com/Tj4m6E2L And heres the current EXE: http://www.mediafire.com/download/4fy4syga2aj8n2j

Thanks for any help you can provide. I am new to C code so keep it simple and stupid for my benefit.


Solution

  • You're missing crucial break statements in your switch, e.g.

    switch(rank)
    {
      case 14:
       {
       if(suite == 'H')
            printf("Your card is the Ace of Hearts!");
       else if(suite == 'C')
            printf("Your card is the Ace of Clubs!");
       else if(suite == 'D')
            printf("Your card is the Ace of Diamonds!");
       else
            printf("Your card is the Ace of Spades!");
       }
      // <<< NB: case 14 "falls through" to case 13 here !!!
      case 13:
        ...
    

    Change this to:

    switch(rank)
    {
      case 14:
       {
       if(suite == 'H')
            printf("Your card is the Ace of Hearts!");
       else if(suite == 'C')
            printf("Your card is the Ace of Clubs!");
       else if(suite == 'D')
            printf("Your card is the Ace of Diamonds!");
       else
            printf("Your card is the Ace of Spades!");
       }
       break; // <<< FIX
      case 13:
        ...
    

    Repeat for all the other missing break statements.