首页 > 解决方案 > 选择你自己的冒险

问题描述

因此,我正在将老板室作为选择您自己的冒险计划的一部分,并且在使 if 语句正常工作时遇到问题。当输入 1 或 2 时,打印语句不打印。

#include <stdio.h>
#include <stdbool.h>
int main()
{
int answer;
bool repeat= true;
printf("\nYou have entered the boss room!!\nWould you like to turn back and allow humanity to be \e[1;31mDESTROYED \e[0m\n \t\tor \n\e[1;31mFIGHT\e[0m the boss and attempt to save the world?\n1.Turn back\n2.Fight\n");
while(repeat) 
{   
    if(scanf("%d",&answer) != 1 || scanf("%d",&answer) != 2)
    {
        printf("Invalid selection. Please selection an action to take.\n");
        printf("1.Turn back\n2.Fight\n");
    } 
    else if(scanf("%d",&answer) == 1) //add string option
    {
        printf("\nYou have choosen to turn back and as a result the world has been destroyed and humanity has perished!!\n\n\t\t\e[1;31mGAME OVER\e[0m\n\n");
        repeat= false;
    }
    else if(scanf("%d",&answer) == 2) //add string option
    {
        printf("\nYou have chosen to fight the boss. The fate of humanity will now be decided. Good luck.\n");    
        repeat= false;
    }  
}   
return 0;
}

标签: c

解决方案


的返回值scanf是它成功找到的参数个数,所以你的测试是不正确的。您需要检查是否scanf返回 1,这意味着它成功解码了一个整数,然后测试answer1 或 2 的值。

但是,如果用户键入的不是整数,例如1.1or ,您仍然会遇到问题I like pie。然后输入缓冲区仍将包含原始输入,您的代码将永远循环。在这种情况下,您需要scanf在循环中再次调用之前清除输入缓冲区。正是scanf(以及其他)的这种弱点使人们不喜欢它。

您可以做的是使用类似fgets将整个输入作为字符串读取的函数,从而每次清除所有输入,然后使用sscanf或类似方法进一步解析该字符串。这样,您可以保持相同的循环和测试结构,而不必担心不合格的输入会使您的循环永远迭代。

我已经重写了您的代码,显示了一种通过fgets.

#include <stdio.h>
#include <stdbool.h>
int main()
{
   char line[80];
   int answer;
   printf("\nYou have entered the boss room!!\nWould you like to turn back and allow humanity to be \e[1;31mDESTROYED \e[0m\n \t\tor \n\e[1;31mFIGHT\e[0m the boss and attempt to save the world?\n1.Turn back\n2.Fight\n");
   while(fgets(line, 80, stdin) != NULL) 
   {
        if(sscanf(line,"%d",&answer) != 1 || (answer != 1 && answer != 2))
        {
            printf("Invalid selection. Please selection an action to take.\n");
            printf("1.Turn back\n2.Fight\n");
        }
        else if(answer == 1) //add string option
        {
            printf("\nYou have choosen to turn back and as a result the world has been destroyed and humanity has perished!!\n\n\t\t\e[1;31mGAME OVER\e[0m\n\n");
            break;
        }
        else // answer == 2  //add string option
        {
            printf("\nYou have chosen to fight the boss. The fate of humanity will now be decided. Good luck.\n");    
            break;
        }  
   }   
   return 0;
}

推荐阅读