gpt4 book ai didi

c - 使用 scanf() 读取字符

转载 作者:太空狗 更新时间:2023-10-29 15:15:00 26 4
gpt4 key购买 nike

此代码用于掷骰子游戏

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

int roll_dice(void);
bool play_game(void);

int main()
{
int i, ch,win = 0,lose = 0;
bool flag;
srand((unsigned)time(NULL));

do
{
flag = play_game();
if(flag)
{
printf("You win!");
win++;
}
else
{
printf("You lose!");
lose++;
}

printf("\n\nPlay again(Y/N)? ");
scanf("%c", &ch);
ch = getchar();
printf("\n");
}while(ch == 'Y' || ch == 'y');

printf("\nWins: %d Losses: %d",win,lose);
return 0;
}

int roll_dice(void)
{
return rand()%6 + rand()%6 + 2;
}

bool play_game(void)
{
int sum = roll_dice();

printf("You rolled: %d\n", sum);
if(sum == 7 || sum == 11)
return 1;
else if(sum == 2 || sum == 3 || sum == 12)
return 0;
else
{
int point = sum;
printf("Your point is: %d\n", point);
do
{
sum = roll_dice();
printf("You rolled: %d\n", sum);
if(sum == 7)
return 0;
}while(point != sum);
return 1;
}
}

我只有代码片段有问题

 printf("\n\nPlay again(Y/N)? ");
scanf("%c", &ch);
ch = getchar();
printf("\n");

我用过,因为无论用户输入 Y 还是 N,它都会在一次迭代后终止。我认为我通过放置 ch = getchar() 吃掉 \n 做错了,我删除了它并在转换说明符之前放置了一个空格并将其替换为 “%c” 也没有用。当我用 %d 替换转换说明符时,它工作正常。
这有什么问题吗?
我访问了这个post它说的和我做的一样。

最佳答案

发布的代码具有未定义的行为,因为 chint 类型并且格式说明符 %c 必须匹配 char.

When I replaced the conversion specifier %d it works fine.

当您切换到 %dscanf()失败,因为 Yy 不是 int,因此不会消耗任何输入(除了前导空格会丢弃后续的换行符循环的迭代)和随后的 ch = getchar() 实际上读取用户输入的字符,并且代码靠侥幸工作。始终检查 scanf() 的返回值,它返回分配的次数。

关于c - 使用 scanf() 读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17497111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com