![]() |
Re: Program to deal 5 cards
In article <3EF5B834.7060706@sonic.net>, stevetux@sonic.net wrote:
>I'm trying to get a program to deal five cards to stdout, randomly >picked from a deck of 52. My best efforts have earned me a segmentation >fault. > >My big hang-up is how to avoid duplicating cards in the deal. Once >I've dealt a card, how do I make sure that that same card is not dealt >again? > >Here's my failed attempt; please help. I'm using s, c, d and h for >spades, clubs, diamonds and hearts, respectively; A for ace, K for >king, Q for queen, J for jack, T for ten. Cards two through nine >are represented by their respective numerals (2 through 9). > >Once again, this program yields a seg fault. > > >#include <stdio.h> >#include <stdlib.h> >#include <time.h> >#include <string.h> > >int main() >{ > > int index, i; > int how_many_dealt = 0; > char *dealt_cards[5]; This should be changed to char dealt_cards[5][3]; because the pointers are uninitialized, e.g. they are set to NULL. > char picked_card[3]; > > char *cards[] = {"As", "Ac", "Ad", "Ah", "Ks", "Kc", "Kd", "Kh", > "Qs", "Qc", "Qd", "Qh", "Js", "Jc", "Jd", "Jh", > "Ts", "Tc", "Td", "Th", "9s", "9c", "9d", "9h", > "8s", "8c", "8d", "8h", "7s", "7c", "7d", "7h", > "6s", "6c", "6d", "6h", "5s", "5c", "5d", "5h", > "4s", "4c", "4d", "4h", "3s", "3c", "3d", "3h", > "2s", "2c", "2d", "2h" > }; This should be changed also to char cards[52][3]; because these are initialized as read-only string literals. > > while (how_many_dealt < 5) { > srand(time(NULL)); > index = rand() % 52; > > /* If the card has been Already Picked ("AP") */ > if (strcmp(cards[index], "AP") != 0) { > strcpy(dealt_cards[how_many_dealt], cards[index]); > how_many_dealt++; > strcpy(cards[index], "AP"); > } else > continue; > } > > for (i = 0; i < 5; i++) > printf("%s ", dealt_cards[i]); > > printf("\n"); > > return 0; >} -- char*c="(&$'&%$&$#'$&$&$&$$$&$#&$'$&$($&$#%$'$$$%$ ((#%$'$$$%$($&$#$$'($$($&" "$#$($&$$$&$$$&$#($$&$%&%$&$#",z,q=0,p=35;main(){f or(;q<8;c++,p^=35){if(*c== 35)++q&&puts("")&&(p=q<6?35:0);for(z=35;z++<*c;)pu tchar(p);}}/*Zach Wegner*/ |
| All times are GMT. The time now is 01:20 AM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.