I am having problems with this function. This is an exercise from the book "C Programming: A Modern Approach" Chapter 10.
Code:
void read_cards(void)
{
char ch, rank_ch, suit_ch;
int rank;
int suit = 0;
Bool bad_card;
int cards_read = 0;
/* Sets all array elements to zero */
for(rank = 0; rank < NUM_RANKS; rank++)
{
hand[rank][suit] = 0;
for(suit = 0; suit < NUM_SUITS; suit++)
hand[rank][suit] = FALSE;
}
while (cards_read < NUM_CARDS)
{
bad_card = FALSE;
printf("Enter a card: ");
rank_ch = getchar();
switch (rank_ch)
{
case '0': exit(EXIT_SUCCESS);
case '2': rank = 0; break;
case '3': rank = 1; break;
case '4': rank = 2; break;
case '5': rank = 3; break;
case '6': rank = 4; break;
case '7': rank = 5; break;
case '8': rank = 6; break;
case '9': rank = 7; break;
case 't': case 'T': rank = 8; break;
case 'j': case 'J': rank = 9; break;
case 'q': case 'Q': rank = 10; break;
case 'k': case 'K': rank = 11; break;
case 'a': case 'A': rank = 12; break;
default: bad_card = TRUE;
}
suit_ch = getchar();
switch (suit_ch)
{
case 'c': case 'C': suit = 0; break;
case 'd': case 'D': suit = 1; break;
case 'h': case 'H': suit = 2; break;
case 's': case 'S': suit = 3; break;
default: bad_card = TRUE;
}
while ((ch = getchar()) != '\n')
if (ch != ' ') bad_card = TRUE;
if (bad_card)
printf("Bad card; ignored.\n");
else
{
hand[0][cards_read] = rank;
hand[1][cards_read] = suit;
printf("hand[1][%d] = %d. \n", cards_read, suit);
cards_read++;
}
}
printf("Rank %d Suit %d. \n", hand[0][0], hand[1][0]);
printf("Rank %d Suit %d. \n", hand[0][1], hand[1][1]);
printf("Rank %d Suit %d. \n", hand[0][2], hand[1][2]);
printf("Rank %d Suit %d. \n", hand[0][3], hand[1][3]);
printf("Rank %d Suit %d. \n", hand[0][4], hand[1][4]);
}
This is the output I get from the command line.
Code:
Enter a card: 2h
hand[1][0] = 2.
Enter a card: 3h
hand[1][1] = 2.
Enter a card: 4h
hand[1][2] = 2.
Enter a card: 5h
hand[1][3] = 2.
Enter a card: 6h
hand[1][4] = 2.
Rank 0 Suit 4.
Rank 1 Suit 2.
Rank 2 Suit 2.
Rank 3 Suit 2.
Rank 4 Suit 2.
The thing I am confused about is when I print out to screen the value stored in hand[1][0] why is it 4 and not 2? I have noticed that it changes value if I enter different cards.
Thanks for any help. If I need to provide any more information I will gladly do so.