c++程序不会退出while循环

C++ Program will not exit while loop

本文关键字:while 循环 退出 程序 c++      更新时间:2023-10-16

当用户输入'Q'或'Q'退出程序时,我的c++程序不会退出下面的while循环。前两个选项工作得很好,并调用相应的函数,但'Quit The program'选项只是无限期地重新开始while循环。

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
    char choice; //Varible to hold the user's choice.
    while (choice != 'Q' || choice != 'q')
    {
        //Display the menu and retrieve the user's choice.
        cout << "Please choose from one of the options below:nn";
        cout << "A. Calculate the total amount of your bill [Enter A]n";
        cout << "B. Calculate your BMI [ENTER B]n";
        cout << "Q. Quit the program [Enter Q]nn";
        cout << "Enter your choice: ";
        cin >> choice;
        //Either calculate the user's bill or their BMI based on their choice.
        if (choice == 'A' || choice == 'a')
        {
            caLculateBillAmount();
        }
        else if (choice == 'B' || choice == 'b')
        {
            calculateBMI();
        }
    }
    return 0;
}

您应该直接使用while (choice !='Q' && choice !='q') {...}。是的,你应该初始化choice为不同于Q和Q的值。就像char choice=0;一样。

问问自己下面的结果是什么:

choice != 'Q' || choice != 'q'

如果选项是'Q',则选项不是'Q',因此测试的右半部分为真。

如果选项是'q',则选项不是'q',因此测试的左半部分为真。

你需要使用&&或者您可以简单地使用toupper(choice) != 'Q'.