c - 选择你自己的冒险
问题描述
因此,我正在将老板室作为选择您自己的冒险计划的一部分,并且在使 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;
}
解决方案
的返回值scanf
是它成功找到的参数个数,所以你的测试是不正确的。您需要检查是否scanf
返回 1,这意味着它成功解码了一个整数,然后测试answer
1 或 2 的值。
但是,如果用户键入的不是整数,例如1.1
or ,您仍然会遇到问题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;
}
推荐阅读
- java - 原因:org.apache.logging.log4j.LoggingException:log4j-slf4j-impl 不能与 log4j-to-slf4j 一起出现
- here-maps-rest - 如何在反应中使用 HEREMAPS 禁用地图中的 3D 建筑视图?
- javascript - 使用 moment.js 从两个变量中设置日期和时间
- asp.net - 通过 365 从 asp.net 发送一封电子邮件,其中的“发件人”电子邮件与用户名不同
- javascript - 通过标识符访问对象
- python - 如何在python中对排列的每一行求和
- flutter - 颤振块 - 错误的状态从块发送到小部件
- scala - 如何将 current_timestamp() 列添加到流数据帧?
- docker - 在 gitlab-runner 容器中更改 config.toml 后参数 URL 未更新
- python - 纸浆 Lp:无法达到变量