使用scanf()读取字符 [英] Reading character with scanf()
问题描述
此代码适用于垃圾游戏。
#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()
吃了 \\\
在转换说明符之前放置一个空格,并替换为
%c
这也没有工作。当我替换转换说明符%d
它工作正常。
这是什么问题?
我访问了这个 post ,这是我说的同样的事情。
I have used, because it terminates after one iteration whatever user input Y
or N
. I thought I am doing wrong by placing ch = getchar()
to eat up \n
, I removed it and placed a space before conversion specifier and replaced it by " %c"
which also did't work.When I replaced the conversion specifier by %d
it works fine.
Is anything going wrong with this?
I visited this post and it is saying same thing I did.
推荐答案
发布的代码具有未定义的行为,因为 ch
code> int 且格式说明符%c
必须与 char
匹配。
The posted code has undefined behaviour because ch
is of type int
and the format specifier %c
must match a char
.
当我替换转换说明符%d时,它工作正常。
When I replaced the conversion specifier %d it works fine.
当您切换到%d
Y 或
,您无法使用 scanf()不是
int
,因此不会消耗任何输入(除了在循环的后续迭代中丢弃新行字符的前导空白空间)和随后的 ch = getchar()
实际上读取用户输入的字符,并且代码通过fluke工作。始终检查 scanf()
的返回值,它返回已完成的分配数。
When you switch to %d
the scanf()
fails, because Y
or y
is not an int
, so no input is consumed (apart from leading whitespace which discards the new line character on subsequent iterations of the loop) and the subsequent ch = getchar()
actually reads the user entered character, and the code works by fluke. Always check the return value of scanf()
, which returns the number of assignments made.
这篇关于使用scanf()读取字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!