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:
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;
}
#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)
staticconst 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/findconstauto pos = valid_letters.find(letter) ;
if( pos == std::string::npos ) return -1 ; // not found, return -1
elsereturn 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' ;
}