C语言测验游戏程序BUG排查:正确输入仍提示错误
测验游戏程序答案判断错误问题排查
开发的测验游戏程序,输入正确答案时始终输出“Wrong!”,无论答案对错都显示错误。以下是第一道题的运行示例:
QUIZ GAME ! ------------------------------------ .1 What year did the C language debut ? : A. 1969 B. 1972 C. 1965 D. 1999 guess: b Wrong!
对应的代码:
#include <stdio.h> #include <ctype.h> int main() { char questions[][100] = {".1 What year did the C language debut ? : ", ".2 Who is credited with creating C ? : ", ".3 what is the predecessor of C ? : "}; char options[][100] = {"A. 1969", "B. 1972", "C. 1965", "D. 1999", "A. Dennis Ritchie", "B. Nikola Teala", "C. John Carmack", "D. Doc Brown", "A. Objective C", "B. B", "C. C++", "D. C#"}; char answers[3] = {'B', 'A', 'B'}; int numberOFquestions = sizeof(questions) / sizeof(questions[0]); char guess; int score; score = 0; printf("QUIZ GAME !\n"); for (int i = 0; i < numberOFquestions; i++) { printf("------------------------------------\n"); printf("%s\n", questions[i]); for (int j = (i * 4); j < (i * 4) + 4; j++) { printf("%s\n", options[j]); } printf("guess: "); scanf("%c", &guess); scanf("%c"); // second scanf helps clear \n from the input buffer // accept lowercase answers guess = toupper(guess); if (guess == answers[i]) { printf("Correct!\n"); score++; } else { printf("Wrong!\n"); } } printf("**********************\n"); printf("FINAL SCORE: %d/%d\n", score, numberOFquestions); return 0; }
问题根源
错误不在你怀疑的for循环中,而是输入处理的scanf调用存在问题:
- 第二行
scanf("%c");缺少指针参数,属于未定义行为,无法正确清除输入缓冲区的换行符。 - 第一行
scanf("%c", &guess)会读取输入缓冲区中的任意字符(包括换行符),如果缓冲区残留换行符,会导致guess被赋值为换行符,经toupper转换后仍与答案字符不匹配,最终输出“Wrong!”。
修复方案
方案1:优化scanf格式字符串(推荐)
删除错误的第二行scanf,在第一行scanf的%c前添加一个空格,让scanf自动跳过所有空白字符(包括换行、空格、制表符):
printf("guess: "); scanf(" %c", &guess); // 开头的空格跳过空白字符
方案2:正确使用第二个scanf
定义一个临时字符变量,用于接收换行符,确保scanf调用参数合法:
printf("guess: "); char dummy; scanf("%c", &guess); scanf("%c", &dummy); // 读取输入后的换行符
修复后的完整代码
#include <stdio.h> #include <ctype.h> int main() { char questions[][100] = {".1 What year did the C language debut ? : ", ".2 Who is credited with creating C ? : ", ".3 what is the predecessor of C ? : "}; char options[][100] = {"A. 1969", "B. 1972", "C. 1965", "D. 1999", "A. Dennis Ritchie", "B. Nikola Teala", "C. John Carmack", "D. Doc Brown", "A. Objective C", "B. B", "C. C++", "D. C#"}; char answers[3] = {'B', 'A', 'B'}; int numberOFquestions = sizeof(questions) / sizeof(questions[0]); char guess; int score = 0; printf("QUIZ GAME !\n"); for (int i = 0; i < numberOFquestions; i++) { printf("------------------------------------\n"); printf("%s\n", questions[i]); for (int j = (i * 4); j < (i * 4) + 4; j++) { printf("%s\n", options[j]); } printf("guess: "); scanf(" %c", &guess); guess = toupper(guess); if (guess == answers[i]) { printf("Correct!\n"); score++; } else { printf("Wrong!\n"); } } printf("**********************\n"); printf("FINAL SCORE: %d/%d\n", score, numberOFquestions); return 0; }
内容的提问来源于stack exchange,提问作者AmineDELTA
相关产品推荐
相关产品推荐

