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

do/while loop with cin.getline parsing to string doesn't compare values to break it

所以我在 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);

但是,当在第一个输入中键入“exit”时,它不会退出循环并进入内部循环。问题出在哪里,可能的解决方案是什么?

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);