// p - pointer to argument // idx - index in argument // default value static int get_number_arg(char* p,int def) { if (isdigit(*p)) { def = atoi(p); } return def; }
static void print_help() { cout<<"Usage: "< cout<<"Bridge Dealer"< cout<<"Example: "< cout< cout<<" -p number of players, value ranges from 1 to 4"< cout<<" /""< cout<<" -n number of deals, default /"1/""< cout<<" -v,--version print version information and exit"< cout<<" -h,--help display this help and exit"< cout< exit(0); }
int main(int argc, char** argv) { int argv_idx = 1; /* active option letter is argv[0][argv_idx] */ int players=1; int number_of_deals=1; bool want_argument=false;
while(argc>0) { if(argv[0][0]=='-') { char c=argv[0][argv_idx++]; switch(c) { case 0: //do nothing argv_idx=-1; break; case '-': // "--" don't take any more options if(strcmp(argv[0]+argv_idx,"version")==0){ print_version(); } else if(strcmp(argv[0]+argv_idx,"help")==0){ print_help(); } argv_idx=-1; break; case 'h': print_help(); break; case 'v': print_version(); break; case 'p': // 1,2,3,4 players, default 1 if (argv[0][argv_idx]){ // "-p{tag}" players=get_number_arg(argv[0]+argv_idx,1); argv_idx=-1; } else{ // "-p {tag}" want_argument=true; } break; case 'n': //number of deals, default 1 if (argv[0][argv_idx]){ // "-n{tag}" number_of_deals=get_number_arg(argv[0]+argv_idx,1); if(number_of_deals<=0) number_of_deals=1; argv_idx=-1; } else{ // "-n {tag}" want_argument=true; } break; default: break; }
//handle options with argument if(want_argument) { if (argv[0][argv_idx]){ cerr< }
--argc; if (argc<1){ cerr< } ++argv; argv_idx = -1;
switch(c) { case 'p': players=get_number_arg(argv[0],1); argv_idx=-1; break; case 'n': number_of_deals=get_number_arg(argv[0],1); if(number_of_deals<=0) number_of_deals=1; argv_idx=-1; break; default: ; //impossible } }
} else{ argv_idx=-1;//do nothing } // If there are no more letters after the current "-", go to next // argument. argv_idx is set to -1 when the current argument is to be // skipped. if (argv_idx <= 0 argv[0][argv_idx] == 0) { --argc; ++argv; argv_idx = 1; } } //init srand(time(0));
//original card //value: spade, 0-12; heart, 13-25; diamond 26-38; cotton 39-51; //array index: west, 0-12; north, 13-25; east 26-38; south 39-51; const int dim=52; int cards[dim];