Stacks and Precedence

Im having trouble wrapping my head around this concept. My current mindset is have a string to read in the variables. If its a letter it goes onto one stack and if is a operator it goes onto another stack. I want to take A+B-C*D and turn it into :
*CD
+AB
2-1 (where 1 is a+b and 2 is C*D)

I have an outline but im not sure what to do about "(" and ")" either.

Im not asking for the whole thing to make made out for me(which would be somewhat helpful because I have a harder version of this to do after this), all I'm askin is for hints or fixes to my code that can help me get to a point that I can fix it on my own at the very least.



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
72
73
74
75
76
77
78
79
80
81
82
83
84
/*Write an object oriented C++ program to translate a C++ assignment statement into
triplet form. You may assume that variables are single characters. Use a precedence
table to decide if operators get pushed or popped. Be sure to give clear directions so
that a person unfamiliar with this process will understand how to execute your solution.*/

#include <iostream>
#include <string>
#include <stack>
using namespace std;


class tripletform {

public:

	void process(const string& x);
	void precedence(const string& x);
	
private:

	stack<char> letters;
	stack<char> operators;
};


void tripletform::precedence(const string& x) {


}

void tripletform::process(const string& x) {

	//int count = x.length();

		for(int i = x.length(); i > -1; i--) {
			if (i <= 'A' || i >= 'z'){
				letters.push(x[i]);
			}
		}

		for(int j = x.length(); j > -1; j--) {
			
			if(j == '('){
				operators.push(x[j]);
			}

			if (j == '='){
				operators.push(x[j]);
			}

			if(j == '*' || j == '/') { 
				operators.push(x[j]);
			}

			if (j == '+' || j == '-' ) {
				operators.push(x[j]);
			}

			if(j == ')'){
				operators.push(x[j]);
			}
			
		}
		
		while(!letters.empty()){
			cout << letters.top();
			letters.pop();
		}
		while(!operators.empty()){
			cout << operators.top();
			operators.pop();
		}
}


int main () {

	string x;
	getline(cin, x);
	tripletform test;
	test.process(x);
	
	cin >> x;
}
Topic archived. No new replies allowed.