C++程序Switch语句不执行、菜单无限循环及无法输入问题求助
故障根因与修复方案
main函数核心问题
- 无输入读取逻辑:定义int类型变量
ch后未执行cin >> ch读取用户输入就直接进入switch分支判断,ch为未初始化的随机值,永远无法匹配对应case,删除无限循环后程序打印完菜单就直接结束运行。 - 无限循环逻辑错误:之前添加的
for(;;)死循环将菜单打印逻辑包含在内,且没有输入读取动作阻塞程序运行,会持续执行菜单打印代码导致无限输出。 - 分支匹配类型不兼容:
ch为int类型,但case判断使用字符常量'1'/'2'等,int类型的数字1与ASCII码为49的字符'1'值不相等,即便读取了输入也无法触发对应分支逻辑。 - 循环结构不合理:若要保留菜单多次选择能力,需将菜单打印、输入读取、switch逻辑全部放置在
for(;;)循环内部。
其余隐藏代码问题
calcAverageGPA函数数组越界:循环条件i <= n会访问下标为n的非法元素,n个元素的合法下标范围为0~n-1,需修改为i < n。showListByGPA函数逻辑失效:if (s[i].getGPA() > gpa);末尾多写分号,判断逻辑完全失效,所有学生信息都会被打印;同时循环条件i < n-1会漏掉最后一个学生,需修改为i < n,且将打印语句放在if判断的分支内部。case 3输出逻辑缺失:查询到对应学生GPA后,仅打印提示文本未输出GPA的具体数值。- 菜单提示缺失:选项5(计算平均GPA)未在菜单中展示。
修复后核心代码示例
// 仅展示修改后的main函数,其余函数按照上述问题点对应修改即可 int main() { int n = 0; int ch; Student s[50]; string name; float GPA; float avg = 0; for(;;){ // 保留无限循环实现多次菜单选择 // 菜单打印放在循环内部 cout << "======================" << endl; cout << "(1): Add a student" << endl; cout << "(2): Print the details of a student" << endl; cout << "(3): Get the GPA of a Student by name." << endl; cout << "(4): Get names of students based on GPA." << endl; cout << "(5): Calculate average GPA." << endl; // 补全菜单选项 cout << "(6): Quit the program." << endl; cout << "Enter your option" << endl; cin >> ch; // 新增输入读取逻辑 switch (ch) { case 1: // 改为int常量匹配 cout << "\nEnter student's name" << endl; cin >> name; cout << "Enter GPA" << endl; cin >> GPA; s[n] = Student(name, GPA); n++; break; case 2: s[0].printDetails(s, n); break; case 3: cout << "\nEnter the name of a student" << endl; cin >> name; GPA = s[0].getGPAbyName(s, n, name); if (GPA == -1) { cout << "\nStudent not found!" << endl; } else cout << "\nGPA is: " << GPA << endl; // 补全GPA输出 break; case 4: cout << "\nEnter GPA: " << endl; cin >> GPA; s[0].showListByGPA(s, n, GPA); break; case 5: avg = s[0].calcAverageGPA(s, n); cout << "\nAverage GPA: " << avg << endl; break; case 6: exit(0); default: // 新增非法输入提示 cout << "\nInvalid option, please try again." << endl; } } }
内容的提问来源于stack exchange,提问作者jacob
相关产品推荐
相关产品推荐

