【问题标题】:How to use character value in if condition (c++)如何在if条件中使用字符值(c ++)
【发布时间】:2023-04-11 03:59:01
【问题描述】:
    {
        cout << "type 3 to add ,type 1 to multiply,type division to divide,type 2 to subtract" << endl;

        cin >> function;

        if (function == 1)
        {
            multiply();
        }

        else if (function == 2)
        {
            subtract();
        }
        else if (function == 3)
        {
            add();
        }
        else if (function == 4)
        {
            division();
        }

        cout << "press x to quit or anything else to restart " << endl;
        cin >> input;
    } while (input !='x');

    system("pause");
    return 0;
}

在此代码中,我无法使用 if 例如,如果(function=='add') 它不起作用 如果我使用if(function='add'),里面的所有东西都会跳到最后一个cout,上面写着

按 x 退出或其他任何东西重新启动

【问题讨论】:

  • 函数在哪里定义?它是一个字符吗?一个整数?见stackoverflow.com/help/mcve
  • 什么是function
  • function='add' 不在您的条件范围内,因此您不会觉得它会跳过所有条件
  • @Detonar:不是真的:它实际上是一个多字符文字。
  • 请提供Minimal, Complete, and Verifiable 示例。将变量命名为 function 具有误导性。

标签: c++ loops while-loop character


【解决方案1】:

'add' 是一个 多字符文字 并且是一个 int 类型(注意单引号字符)。你几乎肯定不想这样做,因为那时你正处于实现定义行为的浑水。

如果您希望能够读取字符串,那么为什么不使用std::string 作为function 的类型,并使用if (function == "add") &c。 ?你甚至可以保留你的符号cin &gt;&gt; function

【讨论】:

    【解决方案2】:

    按照 Bathsheba 的建议,您可以使用 std::string 实现此功能。下面你有一个例子来说明如何做到这一点。

    #include <iostream>
    #include <string>
    
    void multiply() {
        std::cout << "multiplication called" << std::endl;
    }
    void add() {
        std::cout << "add called" << std::endl;
    }
    void subtract() {
        std::cout << "substract called" << std::endl;
    }
    void division() {
        std::cout << "division called" << std::endl;
    }
    
    int main()
    {
        using namespace std;
        string input;
    
        do {
            cout << "type add, multiply, division, or subtract" << endl;
            cin >> input;
    
            if (input == "multiply") {
                multiply();
            }
            else if (input == "substract") {
                subtract();
            }
            else if (input == "add") {
                add();
            }
            else if (input == "division") {
                division();
            }
            else {
                cout << "You inputed: " << input << endl;
                cout << "Command not recognized, please try again" << endl;
                continue;
            }
    
            cout << "press x to quit or anything else to restart ";
            cin >> input;
    
        } while (input != "x");
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-23
      • 2021-07-09
      • 2018-02-20
      • 1970-01-01
      • 2016-03-08
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多