Reputation: 61
My program is working fine and everything but I want it to be perfect. So I've stumbled up on this problem that when my function runs, it prints out the same printf()
statement twice.
Let me show you what I mean, this is how my function looks (skipping main/prototypes)
void decision2(struct CardDeck *deck) {
char choice;
int Ess;
printf("\n%s, Your 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 you like to hit or stand?\n");
scanf("%c", &choice);
}
if (choice == 'H' || choice == 'h') {
printf("You wish to hit; here's your card\n");
Ess = printCards(deck);
if (Ess == 11 && deck->ValueOfSecondPlayer > 10)
{
Ess = 1;
}
deck->ValueOfSecondPlayer += Ess;
printf("Your total is now %d\n", deck->ValueOfSecondPlayer);
if (deck->ValueOfSecondPlayer > 21) {
printf("Sorry, you lose\n");
}
}
if (choice == 'S' || choice == 's') {
printf("You wished to stay\n");
break;
}
}
}
So the thing in my code thats weird is this part:
if (deck->ValueOfSecondPlayer < 21) {
printf("Would you like to hit or stand?\n");
scanf("%c", &choice);
}
The output of the program is becoming this:
k, Your have 4
Would you like to hit or stand?
Would you like to hit or stand?
h
You wish to hit; here's your card
6 of Clubs
Your total is now 10
Would you like to hit or stand?
Would you like to hit or stand?
h
You wish to hit; here's your card
King of Diamonds
Your total is now 20
Would you like to hit or stand?
Would you like to hit or stand?
s
You wished to stay
As you see, the printf prints the statement twice and I can't figure out the program to be honest, so I hope someone do have a solution and an explanation why this is happening?
Upvotes: 3
Views: 2924
Reputation: 11406
There has to be a space before %c
in scanf()
, to clear the previously entered newline \n
:
scanf(" %c", &choice);
Without the space, scanf()
will scan the newline and jump to the beginning of the loop again (after skipping the remaining if
statements), skipping the first if()
, and print "Would you like to hit or stand?\n"
a second time.
Upvotes: 3
Reputation: 134326
The problem here is, with
scanf("%c", &choice);
it reads the previously stored newline
(entered into the input buffer by pressing ENTER key after the first input) and performs one more iteration. You should write
scanf(" %c", &choice); //note the space here
^^
to avoid the newline.
To elaborate, the leading space before the %c
ignores any number of leading whitespace character(s) [FWIW, a newline
is a whitespace character] and wait to get a non-whitespace input.
Upvotes: 6