C在停止之前显示两次

时间:2013-11-09 19:24:26

标签: c function while-loop do-while

这是所谓的功能:

    int onBattle(int level,char nomeheroi[20])
{
        const char *monsternames[4][3] = {
        {"Rat","Bat","Spider"},
        {"Goblin","Orc","Dwarf"},
        {"Dragon","Lich","Banshee"},
        {"Demon","Hydra","Giant Spider"}
        };
        //printf("monster hp:%f  , player hp:%f, player name:%s ",globalvar.monterhp, globalvar.playerhp,nomeheroi);
    char opcaobattle;
    rndMonster(level);

    while((globalvar.monterhp > 0) || (globalvar.playerhp > 0)){
    printf("Monster name:%s\n",monsternames[globalvar.monstercatego][globalvar.monsternivel]);
    printf("Monster Life:%f\n",globalvar.monterhp);
    printf("------------------------------------------\n");
    printf("----------------BattleGround--------------\n");
    printf("------------------------------------------\n");
    printf("Player name:%s\n", nomeheroi);
    printf("Player life:%f\n", globalvar.playerhp);
    printf("----------------------------------------\n");
    printf("------------------Menu------------------\n");
    printf("----------------------------------------\n");
    printf("A - Attack\n");
    printf("D - Defend\n");
    scanf("%c",&opcaobattle);
    switch(opcaobattle)
    {
        case 'a':
        danoPMonster();
        break;

        case 'd':

        break;
    }
  }

  if(globalvar.monterhp <= 0)
    {
        return 0;
    }
  else if(globalvar.playerhp <= 0)
    {
      return 1;
    }
}

这是发生的事情: Show two times

我没有任何问题,这个代码在停止在Scanf之前显示两次,我试过Do While也是同样的事情发生任何帮助? ps:globalvar是一个全局结构,是的,有一个值

1 个答案:

答案 0 :(得分:1)

    scanf("%c",&opcaobattle);

我建议在转换说明符中添加一个空格,以确保它没有在流中使用剩余的换行符。

    scanf(" %c",&opcaobattle);

也可以为交换机设置默认情况:

default:
    printf("Please enter one of the available commands.\n");