作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的程序工作正常,但我希望它是完美的。所以我偶然发现了这个问题,当我的函数运行时,它打印出相同的 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/
我是一名优秀的程序员,十分优秀!