Postfix Exp

I am having a problem with my postfix algorithm

Right off the bat, when I ask the user to enter a postfix expression such as: ab*

the program will say the size of this string is 2, not 3, which is already causing all sorts of problems

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <string>
#include <stack>

using namespace std;
int eval(int var1, int var2, char ops);


int main()
{
	string exp;
	int *vars;
	int var1, var2;
	int result = 0;
	char op;
	stack<char> ops;
	cout << "Please enter a postfix expression" << endl;
	cin.ignore();
	getline(cin, exp);
	cout << exp.length();
	if (exp.length() >= 3)
	{
		//calculate how many expressions
		vars = new int[exp.length()];
		int counter = 0;
		while (counter != exp.length() - 1)
		{
			if (exp[counter] >= 65 && exp[counter] <= 90)
			{
				counter++;
				cout << "Enter a value for: " << exp[counter] << ":" << endl;
				cin >> vars[counter];			
			}
			else if (exp[counter] == '+' || exp[counter] == '-' || exp[counter] == '*' || exp[counter] == '/')
			{
				vars[counter] = '0'; //add a 0 to variable slot 
				counter++;
				ops.push(exp[counter]); //pushes operator
				var1 = counter - 2; //the last 2 variables
				var2 = counter - 1; //the previous variable
				op = ops.top();
				ops.pop();
				result = eval(var1, var2, op);
				
			}
			
		}
	
	}
	else if (exp.length() < 3)
	{
		cout << "Not a complete expression!" << endl;
	}
	cout << "The result of the expression is: " << result << endl;

	system("PAUSE");
	return 0;
		
}

int eval(int var1, int var2, char ops)
{
	switch (ops)
	{
	case '+': return var1 + var2;
	case '*': return var1*var2;
	case '/': return var1 / var2;
	case'-': return var1 - var2;
	default: return 0;
	}
}
You need to remove this cin.ignore () on line 18
Even when I remove cin.ignore(), it still says the size of the string is 2, when it should be 3... it's like it doesn't count "*" or "+" as chars
It works for me
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string expr;

  cout << "Enter expression: ";

  getline(cin, expr);

  cout << "\nYour input: " << expr << "\n\nLength of expr: " << expr.length() << "\n";

  cout << "\nSize of expr: " << expr.size() << "\n\n";
  system("pause");
  return 0;
}
Topic archived. No new replies allowed.