我正在从事一个小型数据库项目。我已经用 switch()
函数创建了一个接口(interface),它应该调用函数并循环直到我选择“EXIT”选项。我通过将指定值设置为 int Loop
变量来控制循环。以这种方式处理这种循环是一种好习惯吗?如果不是,那为什么?在其他函数中,当我有多个条件时,我什至两次使用那种变量。也许我应该做不同的事情?如果我在这种情况下使用 try()、throw()、catch()
异常是否有意义,那么它会是什么样子?这是我的一段代码:
void mainMenu() {
vector<Employee> firmEmployees;
vector<Intern> firmInterns;
int Loop = 0;
while (Loop == 0) {
cout << endl << endl;
cout << "================ EMPLOYEE DATABASE ================" << endl << endl;
cout << " HIRE NEW EMPLOYEE (1)" << endl;
cout << " MANAGE EMPLOYEES (2)" << endl;
cout << " HIRE NEW INTERN (3)" << endl;
cout << " MANAGE INTERNS (4)" << endl;
cout << " EXIT (5)" << endl;
cout << " Choose option... ";
int option;
cin >> option;
if (option < 1 || option > 5 || !cin) {
cout << endl << "---Wrong input!---";
clearInput(); // cleaning cin
} else {
switch (option) {
default:
break;
case 1:
hireEmployee(firmEmployees);
break;
case 2:
employeeMenu(firmEmployees);
break;
case 3:
hireIntern(firmInterns);
break;
case 4:
internMenu(firmInterns);
break;
case 5:
Loop = 1;
break;
}
}
}
}
编辑:另一个例子,更多变量。
void fireEmployee(vector<Employee>& sourceEmployee) {
int repeat = 0;
while (repeat == 0) {
cout << "Enter ID to fire an employee: ";
int id;
cin >> id;
if (cin.fail()) {
clearInput();
cout << "ID number needed!" << endl;
} else {
int buf = 0;
for (auto &i : sourceEmployee) {
if (i.getID() == id) {
i.Fire();
i.setSalary(0);
cout << i.getName() << " " << i.getSurname() << " (" << i.getID() << ") has been fired" << endl;
buf = 1;
repeat = 1;
}
}
if (buf == 0) {
cout << "No employee with ID: " << id << endl;
}
}
}
}
最佳答案
最佳做法是将 while
循环提取到函数中并执行 return
而不是 Loop = 1;
。那将是易于阅读和维护的显式流量控制。例如:
void mainMenuLoop(vector<Employee>& firmEmployees, vector<Intern>& firmInterns) {
for(;;) {
cout << "\n\n================ EMPLOYEE DATABASE ================\n\n";
cout << " HIRE NEW EMPLOYEE (1)\n";
cout << " MANAGE EMPLOYEES (2)\n";
cout << " HIRE NEW INTERN (3)\n";
cout << " MANAGE INTERNS (4)\n";
cout << " EXIT (5)\n";
cout << " Choose option... " << flush; // Must flush here.
int option = -1; // Assign a wrong initial option.
cin >> option;
switch (option) {
case 1:
hireEmployee(firmEmployees);
break;
case 2:
employeeMenu(firmEmployees);
break;
case 3:
hireIntern(firmInterns);
break;
case 4:
internMenu(firmInterns);
break;
case 5:
return;
default:
cout << "\n---Wrong input!---" << endl;
clearInput(); // cleaning cin
break;
}
}
}
void mainMenu() {
vector<Employee> firmEmployees;
vector<Intern> firmInterns;
mainMenuLoop(firmEmployees, firmInterns);
}
另请注意,在
int option;
cin >> option;
如果 cin >> option
失败 option
保留其原始不确定值,它可以是可用选项之一。为它分配一个不是有效选项的初始值更安全,例如 -1
。
关于c++ - 这种控制 while() 循环的做法是好的吗? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50746676/