用scanf()读取字符

时间:2013-07-05 21:31:34

标签: c char scanf specifier

此代码适用于掷骰子游戏

#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,我说的是同样的事情。

4 个答案:

答案 0 :(得分:4)

发布的代码具有未定义的行为,因为ch的类型为int,格式说明符%c必须与char匹配。

  

当我替换转换说明符%d时,它可以正常工作。

当您切换到%d scanf()失败时,因为Yy不是int,所以不会消耗任何输入(除了领先在循环的后续迭代中丢弃新行字符的空格)并且随后的ch = getchar()实际上读取用户输入的字符,并且代码由fluke工作。始终检查scanf()的返回值,该值返回已分配的数量。

答案 1 :(得分:3)

scanf("%c", &ch);
ch = getchar();

这就是你丢失ch中存储的前一个字符的方法。 <怎么样

ch = fgetc(stdin);
while (fgetc(stdin) != '\n')
    ;

代替?

答案 2 :(得分:3)

您使用scanf()转换字符,然后立即用getchar()覆盖它。我不希望它工作,除非你在输入ENTER之前输入“yy”,但是你的第二次确认会失败。

顺便说一句,请使用" %c"中的空格。

答案 3 :(得分:2)

printf("Play again? ");
scanf(" %c", &char);

这段代码对我有用。该项目来自K.N.King的“C编程:现代方法”一书。我之前遇到过这个问题并遇到了同样的问题。在页224上有一个guess.c示例项目,其中包含完全相同的命令“ask”(“再次播放”)。作者使用了scanf(“%c”,&amp; command); (他使用命令而不是ch)它确实有效。我记得我在“掷骰子游戏”项目中使用它但它没有用。可能我错过了一些东西。 总体而言,100%以上的表达确实有效。