为什么我的 C 代码会重复第一个 printf 行?

Why does my c code repeat the first printf line?

我想要一个无限循环,它可以工作。但我不知道为什么它两次打印出同一行。有什么想法吗?

输出:

最后选择:p
你的下一步:RL最后的选择:最后的选择:l
最后选择: 最后选择: r
你的下一步:SL最后选择:最后选择:

到目前为止,这是我的代码:

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while (true)
    {
// Prompt user for input last choice contender
        char c;
        printf("Last choice: ");
        c = getchar();
      // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
// Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
// Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
    }
}

我想我已经为你工作了!

#include <stdio.h>
int main () {
    printf("Last choice: ");
    while (1) {
        char c;
        c = getchar();
        if(c != '\n')
        {
            if (c == 'R'|| c == 'r') {
                printf("Your next move: S\n");
            } else if (c == 'P' || c == 'p') {
                printf("Your next move: R\n");
            } else if (c == 'S' || c == 's') {
                printf("Your next move: P\n");
            } else {
                printf("Use valid input\n");
            }
            printf("Last choice: ");
        }
    }
}

这是因为当您输入密钥然后按回车键时,getchar 会正确获取您的密钥,并且还会得到一个 \n,这是您的回车键。所以你只需要在你的代码中添加一点 if 就可以让它像这样工作:

#include <stdio.h>
#include <cs50.h>

int main ()
{
    while (true)
    {
// Prompt user for input last choice contender
        char c;
        printf("Last choice: ");
        c = getchar();
        if (c != '\n')
            getchar(); //gets the \n if you've given a letter
      // If last choice is R, loser should play S
        if (c == 'R'|| c == 'r')
        {
            printf("Your next move: S");
        }
// Else if last choice is P, loser should play R
        else if (c == 'P' || c == 'p')
        {
            printf("Your next move: R");
        }
// Else if last choice is S, loser should play P
        else if (c == 'S' || c == 's')
        {
            printf("Your next move: P");
        }
    }
}