C语言答题游戏正确答案判定失败的Bug原因排查
问题原因与解决方案
核心问题
你的代码里有两个关键错误导致正确答案无法被识别:
- 无效的
scanf调用:scanf("%c");这个语句缺少必要的指针参数,属于未定义行为,会破坏程序内存结构,导致输入的答案值被篡改或读取异常。 - 输入缓冲区换行符未正确处理:用户输入答案后按回车,输入缓冲区会残留换行符,直接用
scanf("%c", &ans)会在后续循环中读取到这个换行符,导致ans的值变成换行符,自然无法匹配正确答案。
修复后的代码
#include <stdio.h> #include <string.h> #include <ctype.h> int main() { char questions[][100] = { "\n1. what company was the first to create a foldable phone? ", "\n2. what company was the first to create a foldable laptop? ", "\n3. what company was the first to create a full electric car? " }; char options[][100] = { "\nA. apple, B. oppo, C. samsung, D. motorolla", "\nA. Asus, B. MSI, C. Microsoft, D. Gygabyte", "\nA. mazda, B. chevrollet, C. toyota, D. Tesla" }; char answers[] = {'C', 'A', 'D'}; int score = 0; char ans; for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++) { printf("%s", questions[i]); printf("%s", options[i]); printf("\n\nwhat is your answer? "); // 修改这里:用空格跳过空白字符,确保读取到有效答案 scanf(" %c", &ans); ans = toupper(ans); if (ans == answers[i]) { score += 1; printf("\nthat's right!"); printf("\nnext question\n"); } else { printf("\nwrong!"); printf("\nnext question\n"); } } printf("\n\nthe correct answers are: "); for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++) { printf("%c ", answers[i]); } printf("\nyour score is: %d/3", score); }
修改说明
- 删掉了错误的
scanf("%c");语句,避免内存破坏。 - 将读取答案的
scanf("%c", &ans);改为scanf(" %c", &ans);,格式串开头的空格会让scanf自动跳过所有空白字符(换行、空格、制表符等),保证每次读取到的都是用户输入的答案字符,不会被残留的换行符干扰。
内容的提问来源于stack exchange,提问作者Milad Bannourah
相关产品推荐
相关产品推荐

