C ++ While循环终止,即使不满足条件

时间:2018-09-18 17:52:56

标签: c++ while-loop

我希望程序继续要求值进行计算,直到该标志为true,然后程序必须停止,但它只能执行一次。我不知道我是不是使用char的正确方法,或者是否有更好的方法来执行带标志的while循环类型。任何帮助都会很棒。[在此处输入图片描述] [1]

int main()
{
    displayMenu();
    bool flag = false;
    while(!flag)
    {
        int choice = 0; int val1 = 0; int val2 = 0; int ans = 0;
        cout << "Enter your choice (1-5): ";
        cin >> choice;
        cout << "\nEnter integer 1: ";
        cin >> val1;
        cout << "\nEnter integer 2: ";
        cin >> val2;
        if(choice < 0 || choice > 5)
        {
            cout << "\nEnter a choice between 1-5: ";
            cin >> choice;
        }
        if (choice == 1)
        {
          ans = Add(val1,val2);
          cout << "\nResult: " << ans << endl;
        }
        if (choice == 2)
        {
          ans = Subtract(val1,val2);
          cout << "\nResult: " << ans << endl;
        }
        if (choice == 3)
        {
          ans = Multiply(val1,val2);
          cout << "\nResult: " << ans << endl;
        }
        if (choice == 4)
        {
          ans = Divide(val1,val2);
          cout << "\nResult: " << ans << endl;
        }
        if (choice == 5)
        {
          ans = Modulus(val1,val2);
          cout << "\nResult: " << ans << endl;
        }
        char c_flag[] = "n";
        cout << "Press Y or y to continue: ";
        cin >> c_flag;
        if(c_flag == "y" || c_flag == "Y")
        {
            flag = false;
        }
        else
        {
            flag = true;
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:5)

在数据类型为char c_flag[]的情况下,很可能永远不会满足条件c_flag == "y",因为您正在比较两个(不同的)指针值,而不是它们的内容。

改为使用std::string c_flag,至少您的条件应能按预期工作。

您也可以写

char c_flag[] = "y";
...
if (strcmp(c_flag,"y")==0) ...

但是由于以下原因,我更喜欢std::string-variant:使用char c_flag[] = "y",您分配了一个大小为2的数组(包括字符串终止符);使用cin >> c_flag,如果输入多个字符,则将超出数组长度,并产生不确定的行为。相反,使用std::string时,如果需要,变量将“增长”。