我正在尝试使用switch语句为类分配一个非常简单的文本菜单。问题是在调用我在switch语句的不同情况下所做的各种函数时,它们似乎永远不会结束。
考虑到同一个问题似乎在我的switch语句中的所有函数上都发生了,我认为这可能与switch语句本身有关,而不是与单个函数有关,尽管老实说我现在还不知道。
免责声明:我知道我的代码还有很多其他问题,但我只是想为简单起见选择一个大问题。我也希望在代码的其他部分提供建议。 (还没有完成,您可能会从未完成的案例中看到)
示例输出:
==================
1. Admission's Office
2. Student
3. End Program
==================
Enter your choice: 1
Enter the password: 123
******************
1. Add a new student
2. Add new students from a file
3. Drop a student
4. View one students info
5. View all students info
******************
Enter your choice: 1
Enter the first name: First Name
Enter the last name: Last Name
Enter the gender: m
Enter the first name: It should only ask me once
Enter the last name: Why is this looping?
Enter the gender: ????
Enter the first name:
Enter the last name: ???????
Enter the gender: a
Enter the first name: ^C
代码
//main.cpp
int main() {
Student stuAr[SIZE];
int choice, password, userInput;
int numStu = 0;
bool valid;
do {
userMenu();
cin>>choice;
cout<<endl;
switch(choice){
case 1:
cout<<"Enter the password: ";
cin>>password;
cout<<endl;
valid = checkPass(password);
if (valid) {
adminMenu();
cin>>choice;
cout<<endl;
do {
switch(choice) {
case 1:
addStu(stuAr, numStu);
break;
case 2:
addStuFile(stuAr, numStu);
break;
case 3:
cout<<"Enter the student ID: ";
cin>>userInput;
cout<<endl;
dropStu(stuAr, numStu, userInput);
break;
case 4:
cout<<"Enter the student ID: ";
cin>>userInput;
cout<<endl;
viewStu(stuAr, numStu, userInput);
break;
case 5:
viewAllStu(stuAr, numStu);
break;
}
}while(choice != 6);
}
else {
cout<<"The password is wrong."<<endl;
}
break;
case 2:
break;
}
}while(choice != 3);
return 0;
//still main.cpp
//addStu function for case 1 of the nested switch statement
void addStu(Student stuAr[], int& numStu) {
cin.ignore();
cout<<"Enter the first name: ";
stuAr[numStu].setFN();
cout<<endl;
//cin.ignore();
cout<<"Enter the last name: ";
stuAr[numStu].setLN();
cout<<endl;
cout<<"Enter the gender: ";
stuAr[numStu].setGender();
cout<<endl;
numStu++;
return;
}
您永远不会在内部循环中重新读取choice
。
if (valid) {
adminMenu();
cin>>choice; // only done once, therefore do loop never terminates
cout<<endl;
do {
switch(choice) {
case 1:
addStu(stuAr, numStu);
break;
// ...
}
// after switch-case, add:
cin >> choice;
cout << endl;
您永远不会在内部choice
循环中更改do..while
,因此条件choice != 6
将始终为true,除非您是第一次输入。