C语言文本冒险游戏else-if分支输出异常问题求助
问题排查与修复:文本冒险游戏的分支逻辑错误
哥们,一眼就瞅出问题根源了——你用错了C语言里字符串比较的方式!这绝对是新手学C时最常踩的坑之一,咱们一步步把它捋明白:
核心问题:错误的字符串比较逻辑
你写的if (response, "yes")和else if (response, "no")根本不是在比较字符串内容!这里用到的是C语言的逗号运算符,它的规则是:依次执行逗号分隔的每个表达式,最后返回最后一个表达式的值。
换句话说,if (response, "yes")等价于if ("yes")——而字符串常量"yes"在内存里有一个非零的地址,所以这个条件永远为真!不管你输入"yes"、"no"还是别的什么鬼,程序都会直接走第一个if分支,else-if完全没机会执行。
正确解法:用strcmp()函数做字符串比较
C语言里要比较两个字符串的内容,必须用标准库的strcmp()函数,它定义在<string.h>头文件里。用法很简单:
- 当两个字符串完全相等时,
strcmp(a, b)返回0 - 当
a的字典序大于b时,返回正数 - 当
a的字典序小于b时,返回负数
所以你需要先添加头文件#include <string.h>,再把判断条件改成下面这样:
if (strcmp(response, "yes") == 0) { // yes分支代码 } else if (strcmp(response, "no") == 0) { // no分支代码 }
修复后的完整代码
#include <stdio.h> #include <string.h> // 新增:引入strcmp所需的头文件 int main() { char name[1024]; char kname[1024]; char response[1024]; printf("Wanna play a game? First, I need your name.\n"); scanf("%s", name); printf("Your name is %s, huh? I like it.\n", name); printf("Let's get started. You're in the woods. You come across a cat, now you need to name them.\n"); scanf("%s", kname); printf("So, you decided to name them %s? Not what I would've picked, but it's not my pet.\n", kname); printf("You come across a plague doctor. Is that why you came into the woods, to get away from the sickness? Not exactly brave. Anyway, I digress. The plague doctor promises the impossible, tells you that he can and will make you immune with an elixir. Do you take it?\n"); scanf("%s", response); // 修正:用strcmp正确比较字符串内容 if (strcmp(response, "yes") == 0) { printf("You took it, huh? Not what I would've picked, but hey, you seem fine. Uh oh, you don't look so good. I...don't think that was a good idea. Well, there's nothing I can do for you now. Maybe restart the game and see if you can make a better decision. Until next time, old friend."); } else if (strcmp(response, "no") == 0) { printf("Good choice. Come on, I think there's a town up ahead. I'd list off what the town's name was and all that can be found there, but it's currently 11:32 pm on a Saturday and our creator is halfway convinced that this entire program is a fever dream."); } return 0; }
额外小提示
目前你用scanf("%s", response)只能读取不带空格的输入,如果用户输入"yes please"这种带空格的回答,程序只会读到"yes"就停了。如果想支持带空格的输入,可以换成fgets(response, sizeof(response), stdin),不过要记得用response[strcspn(response, "\n")] = '\0'去掉末尾的换行符哦。
内容的提问来源于stack exchange,提问作者Varian




