做...而循环不破坏C ++

时间:2018-07-06 22:02:55

标签: c++ do-while break

当前,我在执行... while循环时遇到问题。

do { 
 // program code here
    cout << "Would you like to run the program again?(yes/no)";
    bool exit = false;
    string strexit;
    do {
        getline(cin, strexit);
        if (strexit == "no") {
            exit = false;
            break;
        }
        else if (strexit == "yes") {
            exit = true;
        }
        else {
            cout << "Enter yes to rerun the program, and no to exit.\n";
        };
    } while (!exit);
    system("cls");
} while (exit);
return 0;
}

我在线研究了如何突破do ... while循环,当条件为true时,它将再次循环,但是如果为false,则退出。 因此,如果您看一下代码,如果用户键入no,则会将exit设置为false,这会将其从较大的do while循环中删除,而break将其从当前的do while循环中删除。 如果用户输入yes,则将exit更改为true,这会将其从当前的do ... while循环中删除,但不会超出第二个循环。

我的问题是(或我需要帮助的地方)是,当用户输入“ no”时,它无法退出do ... while循环,而我对此感到非常困惑。 (它循环回到程序的开头。)

2 个答案:

答案 0 :(得分:13)

在(缩短的)代码中

do
{
    bool exit = false;
    // ...
} while (!exit);

您实际上有 两个不同的 符号,名称为exit。在循环内部,您具有变量。在循环之外并用于条件,您具有函数std::exit。如果您有exit,这将是简单的using namespace std;

在条件中使用的功能 exit将衰减为指向该功能的指针,并且从不为“ false”。因此,条件!exit始终为true,并且存在无限循环。

要解决此问题,您需要做两件事:

  1. 了解using namespace std; is very bad practice

  2. 将变量exit移动到循环外部。而且,您还应该重命名为更具描述性的名称(“ exit”一词有点笼统)。

答案 1 :(得分:3)

我认为@SomeProgrammerDude提供了很好的建议,值得遵循-但我会更进一步,建议移动代码以使用户的响应成为一个单独的函数,这样您就可以更轻松地推理出隔离代码:

bool check_for_exit() { 
    std::string prompt = "\nDo you want to exit the program? ";
    std::string strexit;

    do { 
        std::cout << prompt;
        std::getline(std::cin, strexit);
        prompt = "\nPlease enter yes or no";
    } while (strexit != "yes" && strexit != "no");
    return strexit == "yes";
}

然后,您可以在执行实际工作的代码中使用该函数,顺序如下:

do {
    whatever();
} while (!check_for_exit());

在我看来,这种方法有助于避免您在代码中遇到的许多问题。