【问题标题】:How to commute a string into a mathematical equation [duplicate]如何将字符串转换为数学方程[重复]
【发布时间】:2016-02-12 14:45:03
【问题描述】:

我正在用 C++ 编写方程函数。我的问题是否相当直截了当。我正在阅读文件“4 + 5”。所以我将它存储到一个字符串中。

我的问题:

如何输出 9?因为如果我只是 cout

【问题讨论】:

  • 如果您正在寻找一种快速的方法,我认为没有。您几乎必须自己从头开始编写,这是大学级别的东西。
  • @immibis 好吧,取决于你需要什么。 +,*,() 的递归下降解析器没有花哨的错误处理非常简单。 Fred Overflow 在那个 btw 上做了一个视频。但就目前而言,这个问题肯定太宽泛了。
  • 你的方程总是两个数字的和吗?

标签: c++ c++11


【解决方案1】:

您可能需要做的工作超出您的预期。您需要将每个操作数和运算符分别读入字符串变量。接下来,一旦确认数字字符串确实是整数,就将它们转换为整数。您可能会有一个包含操作数的角色,并且您将执行类似 switch case 之类的操作来确定实际操作数是什么。从那里,您需要对存储在变量中的值执行 switch case 中确定的操作并输出最终值。

【讨论】:

    【解决方案2】:

    http://ideone.com/A0RMdu

    #include <iostream>
    #include <sstream>
    #include <string>
    
    int main(int argc, char* argv[])
    {
        std::string s = "4 + 5";
        std::istringstream iss;
        iss.str(s); // fill iss with our string
    
        int a, b;
        iss >> a; // get the first number
        iss.ignore(10,'+'); // ignore up to 10 chars OR till we get a +
        iss >> b; // get next number 
    
        // Instead of the quick fix I did with the ignore
        // you could >> char, and compare them till you get a +, - , *, etc. 
        // then you would stop and get the next number.
    
        // if (!(iss >> b)) // you should always check if an error ocurred.
                // error... string couldn't be converted to int...
    
        std::cout << a << std::endl;
        std::cout << b << std::endl;
        std::cout << a + b << std::endl;
    
        return 0;
    }
    

    【讨论】:

      【解决方案3】:

      您的输出是“4+5”,因为“4+5”与 ex 的任何其他字符串一样:“abc”,而不是 4 和 5 是整数,而 + 是运算符。 如果涉及的不仅仅是添加 2 个数字,您可以将中缀表达式转换为后缀表达式并使用堆栈进行评估。

      【讨论】:

        猜你喜欢
        • 2014-10-17
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多