can i convert a string to an arithmetic expression?

can i convert a string to an arithmetic expression? or i must do it on hard way?
can i convert a string to an arithmetic expression?

Yes. You can do almost anything in C++ :)

or i must do it on hard way?

Some languages have functionality such as Python's "eval", which can convert strings into Python expressions at execution. This does not exist in a compiled language like C++, although it's possible something like Reflection may be implemented in the future.

Short answer is "yes", you must do it the "hard" way.

I suggest looking into the Shunting-yard algorithm, which can transform a "human-readable" mathematical expression string into a Reverse-Polish notation string, or an expression tree.
https://en.wikipedia.org/wiki/Shunting-yard_algorithm

Also note that various libraries exist to do mathematical equations using strings or build expression trees, but I have not used any enough to suggest a particular one.
Last edited on
i'm trying a hard way, using maybe a hard way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void CalculateExpression(string strMathExpression)
{
    int numbers[3]={0};
    char chOperator[3]={' '};
    for(unsigned int i=0; i<strMathExpression.size() ; i++)
    {
        if(isdigit(strMathExpression[i]))
        {
            numbers[i]= strMathExpression[i];
            cout << numbers[i];

        }
        else
            chOperator[i]=strMathExpression[i];
    }

for now i'm getting problem on converting a char to number.
can you advice me?
(using these method... i know ins't completed. i must another loop)
fixed that part:
we must do '-0':
numbers[i]=static_cast<int>(chr) -'0';
now i can continue with my code. thank you so much
nevermind :)

What you are doing, if you did not understand it...
the alphabet (ascii) table is just numbers, and it is ordered 0123456789 but those are not the integer values, its like (I forget) 40,41,42 or something like that. So you subtract the table value (eg 45 as '5' ) minus the table value of zero (40) giving 5 (the right answer). 40 is just a made up example, I didnt look up the real value.

if you need to do this for anything other than a character, eg "1234" you need stoi() type functions (String TO Int)
Last edited on
are you allowed to have the program make a system call to run the compiler?
zaphraud: i think not
i did something:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

class MathOperators
{
    public:

    enum enumMathOperators
    {
        ParenthesesOpen='(',
        ParenthesesClose=')',
        Add='+',
        Minus='-',
        Multiplication ='*',
        Space=' ',
        Division ='/'
    };

    static bool IsMathOperator(char enMath)
    {
        switch(enMath)
        {
            case ParenthesesOpen:
            case ParenthesesClose:
            case Add:
            case Minus:
            case Multiplication:
            case Space:
            case Division:
                return true;
            default:
                return false;
        }
    }
};

void CalculateExpression(string strMathExpression)
{
    //clean empty spaces
    for(unsigned int i=0; i<strMathExpression.size(); i++)
    {
        if(strMathExpression[i]== ' ' || strMathExpression[i]== '\t')
        {
            strMathExpression.erase(i,1);
            i=0;
        }
    }
    
    //spare the operator and numbers
    //for add them on a vector:
    string strNumber="";
    vector<string> vecOperator;
    int OperatorCount=0;
    char chr[]={'0'};
    for(unsigned int i=0; i<=strMathExpression.size() ; i++)
    {
        chr[0]=strMathExpression[i];
        if(isdigit(chr[0]))
        {
            strNumber+=chr[0];

        }
        else
        {
            if(isdigit(strNumber[0]))
                vecOperator.push_back(strNumber);
            if( MathOperators::IsMathOperator(chr[0])==true)
            {
                //the best for convert char to string:
                stringstream ss;
                string str;
                ss<<chr;
                ss>>str;
                vecOperator.push_back(str);
                OperatorCount++;
            }
            OperatorCount++;
            strNumber="";

        }
    }

    //print actual vector:
    for (unsigned int a=0; a<vecOperator.size();a++)
    {
        cout << vecOperator[a] << " ";
    }
    cout << "\n";

    //making the math:
    for(unsigned int i=0;i<vecOperator.size(); i++)
    {
        if(vecOperator[i]=="+")
        {
            //get result in int:
            int result=stoi(vecOperator[i-1])+ stoi(vecOperator[i+1]);

            //get the result in int to string:
            vecOperator[i-1]= to_string(result);

            //erase the next 2 elements:
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);

            //print the elements after changes:
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            if(i==(vecOperator.size()-2)) break;
            if(vecOperator.size()==3)
                i=0;
            else
                i=-1;
        }

        else if(vecOperator[i]=="-")
        {
            int result=stoi(vecOperator[i-1])- stoi(vecOperator[i+1]);
            vecOperator[i-1]= to_string(result);
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            if(i==(vecOperator.size()-2)) break;
            i=-1;
        }
        else if(vecOperator[i]=="/")
        {
            int result=stoi(vecOperator[i-1])/ stoi(vecOperator[i+1]);
            vecOperator[i-1]= to_string(result);
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            if(i==(vecOperator.size()-2)) break;
            i=-1;
        }
        else if(vecOperator[i]=="*")
        {
            int result=stoi(vecOperator[i-1])* stoi(vecOperator[i+1]);
            vecOperator[i-1]= to_string(result);
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            if(i==(vecOperator.size()-2)) break;
            i=-1;
        }
    }
}

int main()
{
    string strExpression;
    getline(cin, strExpression);
    CalculateExpression(strExpression);
    return 0;
}
heres the output: https://imgur.com/a/WK9vL

i see 2 problems(for now):
1 - sometimes the operators isn't converted correctly from char to string :( ;
2 - why the last math isn't done? (if i do "4+3", it's done)
finally i fix the char type array:
char chr[]={'0','\0'};
what i mean is: i only need 1 char.. true, but we must add the string null terminator: '\0'.
i found the other error:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
void CalculateExpression(string strMathExpression)
{
    //clean empty spaces
    for(unsigned int i=0; i<strMathExpression.size(); i++)
    {
        if(strMathExpression[i]== ' ' || strMathExpression[i]== '\t')
        {
            strMathExpression.erase(i,1);
            i=0;
        }
    }

    //spare the operator and numbers
    //for add them on a vector:
    string strNumber="";
    vector<string> vecOperator;
    int OperatorCount=0;
    
    //we must add a null string terminator
    //for we convert the char to string
    //or we can get unexpected results:
    char chr[]={'0','\0'};
    for(unsigned int i=0; i<=strMathExpression.size() ; i++)
    {
        chr[0]=strMathExpression[i];
        if(isdigit(chr[0]))
        {
            strNumber+=chr[0];
        }
        else
        {
            if(isdigit(strNumber[0]))
                vecOperator.push_back(strNumber);
            if( MathOperators::IsMathOperator(chr[0])==true)
            {
                vecOperator.push_back(chr);
                OperatorCount++;
            }
            OperatorCount++;
            strNumber="";

        }
    }

    //print actual vector:
    for (unsigned int a=0; a<vecOperator.size();a++)
    {
        cout << vecOperator[a] << " ";
    }
    cout << "\n";

    //making the math:
    for(unsigned int i=0;i<vecOperator.size(); i++)
    {
        if(vecOperator[i]=="+")
        {
            //get result in int:
            int result=stoi(vecOperator[i-1])+ stoi(vecOperator[i+1]);

            //get the result in int to string:
            vecOperator[i-1]= to_string(result);

            //erase the next 2 elements:
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);

            //print the elements after changes:
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            
            //before continue the i must be -1
            //when the for restart, the i will be 0:
            i=-1;
            continue;
        }

        else if(vecOperator[i]=="-")
        {
            int result=stoi(vecOperator[i-1])- stoi(vecOperator[i+1]);
            vecOperator[i-1]= to_string(result);
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            i=-1;
            continue;
        }
        else if(vecOperator[i]=="/")
        {
            int result=stoi(vecOperator[i-1])/ stoi(vecOperator[i+1]);
            vecOperator[i-1]= to_string(result);
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            i=-1;
            continue;
        }
        else if(vecOperator[i]=="*")
        {
            int result=stoi(vecOperator[i-1])* stoi(vecOperator[i+1]);
            vecOperator[i-1]= to_string(result);
            vecOperator.erase(vecOperator.begin()+i,vecOperator.begin()+i+2);
            for (unsigned int a=0; a<vecOperator.size();a++)
            {
                cout << vecOperator[a] << " ";
            }
            cout << "\n";
            i=-1;
            continue;
        }
    }
}

(i didn't comment the others operators, because it's the same.)
i need 1 advice: how i control the math priority?
Topic archived. No new replies allowed.