c - 程序两次打印出相同的打印语句

标签 c scanf

我的程序工作正常,但我希望它是完美的。所以我偶然发现了这个问题,当我的函数运行时,它打印出相同的 printf() 语句两次。

让我告诉你我的意思,这就是我的函数的样子(跳过主要/原型(prototype))

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 将语句打印两次,老实说我无法理解该程序,所以我希望有人能提供解决方案并解释为什么会发生这种情况?

最佳答案

这里的问题是,

 scanf("%c", &choice);

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

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

避免换行。

具体来说,%c 之前的前导空格会忽略 任何 个前导空白字符 [FWIW,换行符 是一个空白字符] 并等待获取非空白输入。

关于c - 程序两次打印出相同的打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34828379/

相关文章:

c - nl80211库和cfg80211是如何工作的?

c - 为什么 strtok() 使我的程序返回负值?

c - 获取二叉树节点

c++ - 使用 Catboost C 评估库 API

java - 错误: Connection refused when connecting to socket server

c - scanf() 函数遇到问题

C - fscanf 扫描集在换行后不工作

C:读取单词并在其中包含\n,但不包含空格

c - 使用一个 fscanf 从文件中读取多个字符串

c - ESP8266 GPIO 16 不能用作按钮