Evaluating Postfix Expressions with Alphabet Characters

Hello,
I am writing a program that takes postfix expression strings, such as:

AB+CD-*

And evaluates them such as: (A=1, B=2, C=3...)
The evaluation of AB+CD-* would be -3.

My current code uses a stack of type double to store the answers.
I am required to first convert all letters into numbers. Is there a better way to do this instead of using an if statement? Here is my code. It is not working correctly, and I would like to know if there is a better way to do this besides using an if statement:

double evaluatePostfix(string exprsn)
{
stack<double> Stack;


for (int i = 0; i < exprsn.length(); i++)
{
if (exprsn[i] == 'A')
exprsn[i] = '1';
else if (exprsn[i] == 'B')
exprsn[i] = '2';
else if (exprsn[i] == 'C')
exprsn[i] = '3';
else if (exprsn[i] == 'D')
exprsn[i] = '4';

}

for (int j = exprsn.size() - 1; j >= 0; j--) {

// Push operand to Stack
// To convert exprsn[j] to digit subtract
// '0' from exprsn[j].
if (!isdigit(exprsn[j]))
Stack.push(exprsn[j] - '0');

else {

// Operator encountered
// Pop two elements from Stack
double o1 = Stack.top();
Stack.pop();
double o2 = Stack.top();
Stack.pop();



// Use switch case to operate on o1
// and o2 and perform o1 O o2.
switch (exprsn[j]) {
case '+':
Stack.push(o1 + o2);
break;
case '-':
Stack.push(o1 - o2);
break;
case '*':
Stack.push(o1 * o2);
break;
case '/':
if (o2 = 0) {
cout << "Error!" << endl;
return 0;
}
else {
Stack.push(o1 / o2);
break;
}

}
}
}
return Stack.top();
}

Any help is appreciated. Thank you.
Last edited on
> Is there a better way to do this instead of using an if statement?

If there are many possible letters, a table look-up would be simpler. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

int letter_to_number( char letter ) // 'A' =>1, 'B' => 2 etc.
{
    // 'A' is at position 1, 'B' at position 2 etc. (position zero is not used)
    static const std::string valid_letters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;

    // convert letter to upper case 'a' to 'A' etc.
    letter = std::toupper(letter) ;

    // try to locate the position of the letter in the string
    // https://en.cppreference.com/w/cpp/string/basic_string/find
    const auto pos = valid_letters.find(letter) ;
    if( pos == std::string::npos ) return -1 ; // not found, return -1
    else return pos ; // found, return its value (its position in he string)
}

int main()
{
    char c ;
    while( std::cout << "enter an alpha character [A-Z]: " && std::cin >> c )
        std::cout << "value of letter '" << c << "' is " << letter_to_number(c) << '\n' ;
}

Topic archived. No new replies allowed.