Thread: Cards - Suite and Name

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    55

    Cards - Suite and Name

    Hello all. I am currently writing a program that opens a file, reads the numbers in the file, and takes those numbers and replaces them with words according to suit and name, similar to a deck of cards, and then prints them to another file. 0 is for quiting the program.

    The second column is the suit, the first is the number of the card.

    1 = Clubs
    2 = Diamonds
    3 = Hearts
    4 = Spades

    Example:

    input from file:


    1 4
    11 3
    4 2
    0 0

    output printed to seperate file:

    Ace of Spades
    Jack of Hearts
    4 of Diamonds
    final line quits the program

    -----
    My code so far
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    
    {
    
    FILE *ofp;
    
    ofp = fopen("Cards.dat", "r");
    
    if (ofp == NULL)
    {
     printf("Unable to open Cards.dat");
    }
    
    int numbers[100][2];
    int r, c, n;
    
    for (r = 0; r < 100; ++r)
       {
       for(c = 0; c < 2; ++c)
          {
          fscanf(ofp, "%d", &n);
          numbers[r][c] = n;
    
          if(numbers[r][c] == 0)
             {
             break;
             }
    
          }
       }
    
    printf("%d\n", numbers[0][0]);
    printf("%d\n", numbers[0][1]);
    printf("%d\n", numbers[1][0]);
    printf("%d\n", numbers[1][1]);
    printf("%d\n", numbers[2][0]);
    printf("%d\n", numbers[2][1]);
    printf("%d\n\n", numbers[3][0]);
    
    for(r = 0; r < 100; ++r)
       {
       for(c = 0; c <=1; ++c)
          {
          if(c == 0 && r == 0)
             {
             printf("%d of",numbers[r][c]);
             break;
             }
          }
       }
    
    return 0;
    
    }
    File it's pulling from:
    Code:
    1 4
    11 3
    4 2
    0 0
    As you see at the bottom few lines of code I started with an if statement to check each of the values numbers[r][c]. This quickly led me down a path of many, many if statments and else if statements. What is a better solution to writing this?

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You need a word[][] array, where word[1] is "Ace" and word[4] is "spades", etc.

    Remember that word[n] has the address for the word at row n. So things like this, work fine:

    Code:
    fprintf(filePointer, "%s", word[n]); //write out the word at row n of word[][]

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed