c - Program prints out the same print statement twice -
my program working fine , want perfect. i've stumbled on problem when function runs, prints out same printf()
statement twice.
let me show mean, how function looks (skipping main/prototypes)
void decision2(struct carddeck *deck) { char choice; int ess; printf("\n%s, have %d\n", deck->name2, deck->valueofsecondplayer); while (deck->valueofsecondplayer <= 21) { if (deck->valueofsecondplayer == 21) { printf("you got 21, nice!\n"); break; } if (deck->valueofsecondplayer < 21) { printf("would hit or stand?\n"); scanf("%c", &choice); } if (choice == 'h' || choice == 'h') { printf("you wish hit; here's card\n"); ess = printcards(deck); if (ess == 11 && deck->valueofsecondplayer > 10) { ess = 1; } deck->valueofsecondplayer += ess; printf("your total %d\n", deck->valueofsecondplayer); if (deck->valueofsecondplayer > 21) { printf("sorry, lose\n"); } } if (choice == 's' || choice == 's') { printf("you wished stay\n"); break; } }
}
so thing in code thats weird part:
if (deck->valueofsecondplayer < 21) { printf("would hit or stand?\n"); scanf("%c", &choice); }
the output of program becoming this:
k, have 4 hit or stand? hit or stand? h wish hit; here's card 6 of clubs total 10 hit or stand? hit or stand? h wish hit; here's card king of diamonds total 20 hit or stand? hit or stand? s wished stay
as see, printf prints statement twice , can't figure out program honest, hope have solution , explanation why happening?
the problem here is, with
scanf("%c", &choice);
it reads stored newline
(entered input buffer pressing enter key after first input) , performs 1 more iteration. should write
scanf(" %c", &choice); //note space here ^^
to avoid newline.
to elaborate, leading space before %c
ignores any number of leading whitespace character(s) [fwiw, newline
whitespace character] , wait non-whitespace input.
Comments
Post a Comment