我的程序运行正常,除了我希望它是完美的.所以我偶然发现了这个问题,当我的函数运行时,它会打印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;
}
}
Run Code Online (Sandbox Code Playgroud)
}
所以我的代码中的东西很奇怪就是这部分:
if (deck->ValueOfSecondPlayer < 21) {
printf("Would you like to hit or stand?\n");
scanf("%c", &choice);
}
Run Code Online (Sandbox Code Playgroud)
该计划的输出正在变为:
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
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,printf打印了两次声明,说实话我无法弄清楚程序,所以我希望有人能找到解决方案并解释为什么会发生这种情况?
这里的问题是,与
scanf("%c", &choice);
Run Code Online (Sandbox Code Playgroud)
它读取先前存储的newline(ENTER在第一次输入后按键输入到输入缓冲区中)并再执行一次迭代.你应该写
scanf(" %c", &choice); //note the space here
^^
Run Code Online (Sandbox Code Playgroud)
避免换行.
详细说明,在%c忽略任意数量的前导空格字符[FWIW,a newline是空格字符] 之前的前导空格并等待获得非空白输入.