Untitled
unknown
c_cpp
3 years ago
1.0 kB
10
Indexable
string topostfix(string myString){
char myChar[myString.length()];
strcpy(myChar, myString.c_str());
stack<char> s_op;
string result = "";
for(int i = 0; i < myString.length(); i++){
if(myChar[i] != '*' && myChar[i] != '+' && myChar[i] != '-' && myChar[i] != '/' && myChar[i] != '(' && myChar[i] != ')'){
cout << myChar[i]; // for step-by-step output
result += myChar[i];
}
else if (myChar[i] == '(') {
cout << myChar[i] << "\t\t";
s_op.push(myChar[i]);
}
else if(myChar[i] == ')'){
while(s_op.top() != '('){
result += s_op.top();
s_op.pop();
}
s_op.pop(); // pop the opening parenthesis
}
else{ // if char is an operator
while(!s_op.empty() && precedence(s_op.top()) >= precedence(myChar[i])){
result += s_op.top();
s_op.pop();
}
cout << myChar[i];
s_op.push(myChar[i]);
}
cout << setw(40) << result << endl;
}
while(!s_op.empty()){
result += s_op.top();
s_op.pop();
}
return result;
}
Editor is loading...