我正在尝试使用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
循环中更改do..while
,因此条件choice != 6
始终为true,除非您是第一次输入。
关于c++ - 在switch语句中调用函数时,似乎永无休止的循环的问题(即使函数不包含循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60316319/