Search code examples
c++stackprefixpostfix-notation

Reading a postfix expression as a string from a txt file


This is part of my C++ assignment. I need to write three functions in the project. When i start my work, I found a huge problem, the first function.

First of all, the program is like this:

  1. Open the postfix expression file
  2. Use getline to read line by line (each line is an expression)
  3. Evaluate the expression step by step

I know that I need to call the function to know the next operand and then to calculate the intermediate result. The nextOperand function returns the value of the next operand (datatype: double) that starts at index I of the input string.

This is what I have now:

double nextOperand(const string& expr, int& i)
{
    // You can make use of the function stod(string) string-to-double,
    // and the function substring() to extract an operand from the expression:
    // Example:
    //   string myExpression = "1.5 2.3 +";
    //   int pos = 0;
    //   int len = 3;
    //   string opderand = myExpression.substr(pos, len); 
    //   double value = stod(opderand);
    stack<char> temp;
    string temp1;

    while(expr[i] != ' ' && !isOperator(expr[i]))
    {
        temp.push(expr[i]);
        i++;
    }

    while(!temp.empty())
    {
        temp1 = temp.top() + temp1;
        temp.pop();
    }
    if(temp1 != "\0")
    {
        double value = stod(temp1);
        return value;
    }
    else 
        return 0;
}

The function to evaluate postfix and prefix expressions are not yet programmed. I wish to finish this nextOperand function first to continue.


Solution

  • I think you have over complicated this. I would use the suggestions you have in the comments at the start of the function about using the substring function. You could then use something like your first while loop to get the index of the first non-operand character. Using the example input of "1.5 2.3 +" as per the comments you could do something like this:

    int j = i;
    while(j < expr.size() && expr.at(j) != ' ' && !isOperator(expr.at(j))) {
            j++;
        }
    

    j is the variable used to keep track of where the end of the operand is in the string expr, j should then equal 3 for the example input

    Then just do:

    string operand = expr.substr(i, j); 
    return stod(operand);