c++ - C++ 类方法:从另一个方法调用方法会跳过代码块
问题描述
在尝试在 C++ 中练习 OOP(具有 Java OOP 经验)时,我正在尝试创建一个小程序来跟踪患者并根据队列对其进行治疗。
在我的 PatientManager 类中,我正在实现 4 种方法。启动程序的 start() 方法、newPatient() 方法、nextPatient() 方法和 waitingList() 方法。我有 start() 运行 while(true) ,它可以根据用户输入调用其他 3 种方法中的任何一种。
我已经准备好了 start() 和 newPatient() 并且在测试它时,我似乎无法正确调用 newPatient()。调试器看起来好像 start 跳转到 newPatient ,然后跳过方法中的所有内容,除了 cin.clear() 和 cin.ignore() ,然后返回到 start() 以请求另一个用户输入。我无法弄清楚出了什么问题。
class PatientManager {
private:
//Make a priority queue object
priority_queue<Patient> list;
int order = 1;
public:
PatientManager() {
this->list = list;
}
void newPatient() {
string name;
int emergency;
bool done = false;
cout << "Enter patient's name: ";
cin >> name;
cout << endl << "Enter emergency [1 (low) to 5(life-and-death)]: ";
while (!done) {
try {
cin >> emergency;
while(emergency >5 || emergency <=0) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "(x) Wrong choice. Try again: " << endl;
cin >> emergency;
}
if (cin.fail()) {
throw (emergency);
}
order++;
//list.add the patient
list.push(Patient(name,emergency,order));
done = true;
} catch (string e) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "(x) Wrong choice. Try again: " << endl;
}
}
}
void nextPatient() {
}
void waitingList() {
}
void start() {
cout << "-------------------------" << endl;
cout << " (1) New Patient\n";
cout << " (2) Next Patient\n";
cout << " (3) Waiting List\n";
cout << " (4) Exit\n";
cout << "-------------------------" << endl;
while (true) {
int item = 0;
try {
cout << "Choose an item from the menu: ";
cin >> item;
//Not sure if this is needed
// if (item < 1 || item > 4);
// throw -1;
if (cin.fail()) {
throw exception();
}
} catch (exception e) {
cout << "(x) Wrong choice." <<endl;
item = 0;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
if(item == 1) {
this->newPatient();
} else if(item == 2) {
this->nextPatient();
} else if(item == 3) {
this->waitingList();
} else if(item == 4) {
cout << "Program terminated. Goodbye!\n";
exit(0);
} else if (item < 0|| item >4){
cout << "(x) Wrong choice." <<endl;
item = 0;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
}
}
}
};
我从我的主类创建并调用 PatientManager.start() 并且还有一个单独的 Patient 类。
任何帮助表示赞赏!
解决方案
推荐阅读
- c++ - 为什么代码会抛出非法内存访问错误
- javascript - Angular *ngFor“id”标签生成不正确与`mat-button-toggle`
- azure-devops - 我可以将现有的 NuGet 包上传到 Azure DevOps 工件源吗?
- javascript - 如何使用 Tornado > 4.1 从 HTML5 表单上传大文件
- python - 如何使用 GPU 使用 tf.lite.Interpreter(在 python 中)运行 tflite 模型(*.tflite)?
- xquery - xquery 根据某些条件跳过 xml 记录
- html - HTML 输入表单中的更改不会影响 DOM
- mongodb - 如何在mongodb中获取与某个查询匹配的第一条记录?
- excel - 通过 VLOOKUP 公式中的变量 VBA 名称引用工作表
- javascript - 如何将 onFormSubmit(e) 和 onEdit(e) 嵌套在一起