So I have this type of "menu" in a do/while loop
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);
However, when typing "exit" on the first input, it doesn't exit the loop and goes into the inner one. Where is the issue and what would be possible solutions?
p.s. When running only the inner do/while loop it works correctly.
CodePudding user response:
You are using the same choice
buffer to manage both loops.
The outer loop's while
check is not reached until the inner loop is finished first, and the inner loop only breaks when choice
is "back"
. So, by the time the outer loop's while
check is reached, choice
will never be "exit"
.
Try this instead:
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);