do/while 循环与 cin.getline 解析为字符串不会比较值来破坏它



所以我有这种类型的"菜单";在do/while循环中

do {
cout << "Press 0 to export IDs, exit to exit, or any key to continue to menu:n";
cin.getline(choice, sizeof(choice));
if (strcmp(choice, "0") == 0) {
planesManager.exportIds(idsArray, arrSize);
cout << "Would you like to Sort them?[y/n]n";
cin >> choice;
if (strcmp(choice, "y") == 0) {
int low = 0;
int high = arrSize - 1;
quickSort(idsArray, low, high);
}
cout << "Would you like to print them?[y/n]n";
cin >> choice;
if (strcmp(choice, "y") == 0) {
printArray(idsArray, arrSize);
}
}
do {
cout << ">Would you like to create, search, edit, or go back?n";
cin >> choice;
if (strcmp(choice, "create") == 0) {
planesManager.createEntry();
} else if (strcmp(choice, "search") == 0) {
planesManager.searchEntry();
} else if (strcmp(choice, "edit") == 0) {
planesManager.editEntry();
}
} while (strcmp(choice, "back") != 0);
cin.ignore();
} while (strcmp(choice, "exit") != 0);

然而,当键入";退出";在第一次输入时,它不会退出循环,而是进入内部循环。问题在哪里?可能的解决方案是什么?

p.s.当只运行内部do/while循环时,它可以正常工作。

您使用相同的choice缓冲区来管理两个循环。

直到内部循环首先完成,才达到外部循环的while检查,并且只有当choice"back"时,内部循环才会中断。因此,当达到外循环的while检查时,choice将永远不会是"exit"

试试这个:

do {
cout << "Press 0 to export IDs, exit to exit, or any key to continue to menu:n";
cin.getline(choice, sizeof(choice));
if (strcmp(choice, "exit") == 0) break; // <-- move this here!
if (strcmp(choice, "0") == 0) {
planesManager.exportIds(idsArray, arrSize);
cout << "Would you like to Sort them?[y/n]n";
cin >> choice;
if (strcmp(choice, "y") == 0) {
quickSort(idsArray, 0, arrSize - 1);
}
cout << "Would you like to print them?[y/n]n";
cin >> choice;
if (strcmp(choice, "y") == 0) {
printArray(idsArray, arrSize);
}
}
do {
cout << ">Would you like to create, search, edit, or go back?n";
cin >> choice;
if (strcmp(choice, "create") == 0) {
planesManager.createEntry();
} else if (strcmp(choice, "search") == 0) {
planesManager.searchEntry();
} else if (strcmp(choice, "edit") == 0) {
planesManager.editEntry();
}
} while (strcmp(choice, "back") != 0);
cin.ignore();
} while (true);

最新更新