带有小数和多位数的C ++后缀表达式

时间:2018-10-20 22:33:09

标签: c++ string parsing decimal

我正在努力使用带小数的后缀表达式。我不知道如何将字符串转换为小数或两位数...该程序适用于数字1-9。

我怎样才能使小数成为可能?

该函数必须将字符串作为参数。我的功能:

double evalPostfix(string& input)
{
    stack<double> s;
    int i = 0;
    char ch;
    double val;

    while (i < input.size())
    {

        ch = input[i];
        if (isdigit(ch))
        {
            //Converting and pushing digit into stack
            s.push(ch - '0');
        }



    return val;
}

1 个答案:

答案 0 :(得分:0)

类似的东西:

#include <limits>
#include <stack>
#include <string>
#include <sstream>
#include <iostream>

double eval(double lhs, double rhs, char op)
{
    switch (op) {
    case '+': return lhs + rhs;
    case '-': return lhs - rhs;
    case '*': return lhs * rhs;
    case '/':
        if (rhs != 0)
            return lhs / rhs;
    }

    return std::numeric_limits<double>::quiet_NaN();
}

double evalPostfix(std::string const &input)
{
    std::stack<double> values;
    std::stack<char> ops;
    std::stringstream ss{ input };

    for(;;) {
        for (;;) {
            auto pos{ ss.tellg() };  // remember position to restore if
            double value;
            if (!(ss >> value)) {   // extraction fails.
                ss.clear();
                ss.seekg(pos);
                break;
            }
            values.push(value);
        }

        char op;
        if (!(ss >> std::skipws >> op))
            break;

        if (op != '+' && op != '-' && op != '*' && op != '/') {
            std::cerr << '\'' << op << "' is not a valid operator!\n\n";
            return std::numeric_limits<double>::quiet_NaN();
        }

        if (values.size() < 2) {
            std::cerr << "Not enough values!\n\n";
            return std::numeric_limits<double>::quiet_NaN();
        }

        double op2{ values.top() };
        values.pop();
        double op1{ values.top() };
        values.pop();
        values.push(eval(op1, op2, op));
    }

    if (values.size() > 1) { // if we got here and there is more than 1 value left ...
        std::cerr << "Not enough operators!\n\n";
        return std::numeric_limits<double>::quiet_NaN();
    }

    return values.top();
}

int main()
{
    std::cout << "Enter the postfix expression: ";
    std::string exp;
    std::getline(std::cin, exp);
    double result = evalPostfix(exp);
    std::cout << "==> evaluates to " << result << '\n';
}