2016-01-16 122 views
3

我的程序工作正常,但我希望它是完美的。所以我偶然發現了這個問題,當我的函數運行時,它將兩次打印出相同的printf()語句。程序打印兩次相同的打印語句

讓我告訴你我的意思是,這是我的函數如下(跳過主/原型)

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; 
    } 
} 

}

所以,在我的代碼的東西那怪異這是怎麼組成部分:

if (deck->ValueOfSecondPlayer < 21) { 
     printf("Would you like to hit or stand?\n"); 
     scanf("%c", &choice); 
    } 

的程序的輸出是變這樣的:

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 

正如你所看到的那樣,printf打印了兩次這個語句,並且我無法弄清楚這個程序是否誠實,所以我希望有人確實有解決方案並解釋爲什麼會發生這種情況?

+1

您只使用%c的一個字符,但要輸入它,請按ENTER,這是一個新字符。要麼忽略\ r和\ n,要麼可能使用fgets。 – LSerni

回答

6

這裏的問題是,與

scanf("%c", &choice); 

它讀取先前存儲newline(通過按進入第一輸入之後密鑰輸入到所述輸入緩衝器)和執行一個多迭代。你應該寫

scanf(" %c", &choice); //note the space here 
     ^^ 

避免換行。

爲了詳細說明,領先的空間%c忽略之前的任何領先的空白字符(S)號[FWIW,一個newline是一個空白字符],並等待得到一個非空白輸入。

+0

不知道這個,非常感謝你的解釋! –

+0

@phil_sw不客氣:) –

3

必須有%c前的空間scanf(),以清除先前輸入的換行符\n

scanf(" %c", &choice); 

沒有空間,scanf()將掃描換行,並再次跳轉到循環的開始(後跳過剩餘的if聲明),跳過第一個if(),並且再次打印"Would you like to hit or stand?\n"