程序打印两次相同的打印语句

时间:2016-01-16 14:59:11

标签: c scanf

我的程序工作正常,除了我希望它是完美的。所以我偶然发现了这个问题,当我的函数运行时,它会打印两次相同的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打印了两次声明,说实话,我无法弄清楚程序,所以我希望有人能找到解决方案并解释为什么会发生这种情况?

2 个答案:

答案 0 :(得分:6)

这里的问题是,

 scanf("%c", &choice);

它读取先前存储的newline(在第一次输入后按 ENTER 键进入输入缓冲区)并再执行一次迭代。你应该写

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

避免换行。

详细说明,%c之前的前导空格忽略任何数量的前导空白字符[FWIW,newline是一个空格字符]并等待得到一个非空白输入。

答案 1 :(得分:3)

%c scanf()之前必须有一个空格,以清除之前输入的换行符\n

scanf(" %c", &choice);

如果没有空格,scanf()将扫描换行符并再次跳转到循环的开头(跳过剩余的if语句后),跳过第一个if(),并打印{ {1}}第二次。