how can i make a program by using like this(25/6+3-83/2)to get the sum of them?

Dani AI

Generated

Short summary: for an expression evaluator either convert infix → RPN (the shunting‑yard technique) and then evaluate the RPN, or write a recursive‑descent parser for a fuller grammar. correctly pointed out operator precedence; ’s recursive‑descent tip is good if you later add functions/variables; ’s shunting‑yard pointer is the simplest robust choice for plain arithmetic. Note the original post’s example has formatting glitches — make sure the input uses plain operator characters and parentheses.

Key points before coding: tokenize numbers (allow decimal points), treat a leading unary plus/minus as part of the number token, ignore whitespace, implement precedence (*/ > +-) and left associativity, validate characters and parentheses, and decide whether division should be floating (use double) or integer. Always check for division by zero and malformed input.

A compact C++ shunting‑yard + RPN evaluator (handles decimals and unary leading sign):

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <cctype>
#include <stdexcept>

using namespace std;

bool isUnarySign(const string &s, size_t pos) {
    if (s[pos] != '+' && s[pos] != '-') return false;
    if (pos == 0) return true;
    size_t j = pos;
    while (j > 0) { --j; if (!isspace((unsigned char)s[j])) {
        char pc = s[j]; return pc=='(' || pc=='+' || pc=='-' || pc=='*' || pc=='/';
    }}
    return true;
}

vector<string> tokenize(const string &s) {
    vector<string> t; size_t i=0, n=s.size();
    while (i<n) {
        char c = s[i];
        if (isspace((unsigned char)c)) { ++i; continue; }
        if (isdigit((unsigned char)c) || c=='.' ||
            ((c=='+'||c=='-') && isUnarySign(s,i) && i+1<n && (isdigit((unsigned char)s[i+1])||s[i+1]=='.'))) {
            size_t j=i; if (s[j]=='+'||s[j]=='-') ++j; bool dot=false;
            while (j<n && (isdigit((unsigned char)s[j])||s[j]=='.')) {
                if (s[j]=='.') { if (dot) break; dot=true; } ++j;
            }
            t.push_back(s.substr(i,j-i)); i=j; continue;
        }
        if (string("+-*/()").find(c)!=string::npos) { t.push_back(string(1,c)); ++i; continue; }
        throw runtime_error(string("Invalid char: ")+c);
    }
    return t;
}

int prec(const string &op){ if(op=="+"||op=="-") return 1; if(op=="*"||op=="/") return 2; return 0; }

vector<string> toRPN(const vector<string>& tokens) {
    vector<string> out; stack<string> ops;
    for (auto &tk: tokens) {
        if (!tk.empty() && (isdigit((unsigned char)tk[0]) || tk[0]=='.' || (tk.size()>1 && (tk[0]=='+'||tk[0]=='-'))))
            out.push_back(tk);
        else if (tk=="+"||tk=="-"||tk=="*"||tk=="/") {
            while (!ops.empty() && ops.top()!="(" && prec(ops.top())>=prec(tk)) { out.push_back(ops.top()); ops.pop(); }
            ops.push(tk);
        } else if (tk=="(") ops.push(tk);
        else if (tk==")") { while(!ops.empty() && ops.top()!="("){ out.push_back(ops.top()); ops.pop(); } if (ops.empty()) throw runtime_error("Mismatched ()"); ops.pop(); }
    }
    while (!ops.empty()) { if (ops.top()=="("||ops.top()==")") throw runtime_error("Mismatched ()"); out.push_back(ops.top()); ops.pop(); }
    return out;
}

double evalRPN(const vector<string>& rpn) {
    stack<double> st;
    for (auto &tk: rpn) {
        if (!tk.empty() && (isdigit((unsigned char)tk[0])||tk[0]=='.'||(tk.size()>1&&(tk[0]=='+'||tk[0]=='-')))) st.push(stod(tk));
        else {
            if (st.size()<2) throw runtime_error("Bad expression");
            double b=st.top(); st.pop(); double a=st.top(); st.pop();
            if (tk=="+") st.push(a+b); else if (tk=="-") st.push(a-b);
            else if (tk=="*") st.push(a*b); else if (tk=="/") { if (b==0) throw runtime_error("Div by zero"); st.push(a/b); }
            else throw runtime_error("Unknown op");
        }
    }
    if (st.size()!=1) throw runtime_error("Bad expression");
    return st.top();
}

double evaluate(const string &s){ return evalRPN(toRPN(tokenize(s))); }

int main(){
    string line;
    if (!getline(cin,line)) return 0;
    try { cout << evaluate(line) << '\n'; }
    catch (exception &e) { cerr << "Error: " << e.what() << '\n'; }
}

Notes and troubleshooting: test with leading negatives, nested parentheses and extra spaces. If functions (sin, pow) or variables are needed later, a recursive‑descent parser or a mature expression library will be easier to extend. Complexity of this shunting‑yard + RPN approach is linear in the length of the input.

Recommended Answers

All 4 Replies

Do you mean you need a program that can accept inputs in the style of your example and correctly determine the value?
I would separate the string on the mathmatical operators (+,-,x, /) and bracket, then use the BODMAS rule to figure out the order for which the operations take place.
But your question is unclear. Am I on the right track?

It is a matter of operator precidence. Multiplication and division are of equal precidence, as are addition and subtraction. Multiplication and division have higher precidence than addition or subtraction. Therefore, you must put the desired expressions inside parentheses. IE: (2*5/6+3-8*3/2) would be likely equivalent to ((2*5)/6)+3-((8*3)/2). Is this your intention? Other possibilities could be (2*(5/6))+((3-8)*(3/2)). There are other permutations that could be applied, and in most cases the results are very different.

This is mostly done with what is called a recursive descent parser

This is mostly done with what is called a recursive descent parser

See also the shunting-yard algorithm.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.