当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题



我正试图使用类赋值的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;

您从未在内部do..while循环中更改choice,因此条件choice != 6将始终为true,除非您第一次输入它。

最新更新