如何在 C++ 中计算字符串的算术运算

how to evaluate arithmetic operation from string in c++

本文关键字:字符串 算术运算 计算 C++      更新时间:2023-10-16

我正在努力解决C ++中与字符串相关的问题。

假设我有一个字符串 s="6*6+4*8+6/6/6-632+81";

我的主要目标是从字符串进行算术运算。 因此,在下面的代码中,当整数值为 1 位整数时,我得到了正确的结果。

字符串数学[]="1+2"; 结果:3;

但是当字符串数学[]="10+20"那么 结果为:2;

    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
    int A,B,val;
        char math[]="1+2";
        //char math[]="10+20";
        for (int i = 0 ; math[i]!=NULL; i++)
        {
            char ch =math[i];
             if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
             {
                  char ch2=math[i-1];
                 A=(ch2-'0');

                 char ch3=math[i+1];
                 B=(ch3-'0');
                 switch (ch) /* ch is an operator */
                {
                case '*':
                    val = A * B;
                    break;
                case '/':
                    val = A / B;
                    break;
                case '+':
                    val = A + B;
                    break;
                case '-':
                    val = A - B;
                    break;
                }
             }
            if ( math[i] == NULL)
            {
                break;
            }
        }

    cout<<val<<endl;
    }

所以我意识到问题是选择 A 和 B 的值.这里我没有选择整个数字。 所以我希望我的 A 是 10 和 B 20.但我的程序选择 A=0 和 B=2.所以为了得到整个数字 .like A=10,我在代码中进行了这些更改[仅用于 A.As 测试]。

        if(ch == '+' || ch == '-' || ch == '*' || ch == '/')
        {
         char total;
         int k=i-1;
         cout<<"k="<<k<<endl;
         char p;
         p=math[k];
         for(;k>-1 && isdigit(p)==true;k--)
         {
             char c=math[k];
             cout<<"c"<<c<<endl;
             total=math[i-1];
             total=total+c;
         }
         char ch2=total;
         // char ch2=math[i-1];
        cout<<"ch2:"<<total<<endl;
         A=(ch2-'0');
         cout<<"A="<<A<<endl;

但是现在对于 A 来说,我得到了垃圾价值。现在我该如何解决这个问题。更具体地说,获取 A=10 和 B=20 的值,并得到此数学表达式的正确结果。

使用 std::string 和 std::stringstream like

#include <iostream>
#include <sstream>
#include <string>
using std::cout;
using std::string;
using std::stringstream;
void func(double &result, char op, double num);
int main() {
    string math = "6*6+4*8+6/6/6-632+81";
    stringstream mathStrm(math);
    double result;
    mathStrm >> result;
    char op;
    double num;
    while (mathStrm >> op >> num) {
        cout << "op: " << op << ", num: " << num << 'n';
        func(result, op, num);
    }
    cout << result << 'n';
}

void func(double &result, char op, double num) {
    switch (op) {
        case '+':
            result += num;
            break;
        case '-':
            result -= num;
            break;
        case '*':
            result *= num;
            break;
        case '/':
            result /= num;
    }
}

请注意,字符串是从左到右计算的,没有优先级。