In: Computer Science
INFIX2POSTFIX.CPP
#include "stack.hpp"
using namespace std;
// Auxiliary method, you probably find it useful
// Operands are all lower case and upper case characters
bool isOperand(char c){
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
// Auxiliary method, you probably find it useful
int precedence(char c)
{
if(c == '+' || c == '-'){
return 0;
}
if(c == '*' || c == '/'){
return 1;
}
if(c == '^'){
return 2;
}
return -1;
}
int main(){
freopen("input_infix2postfix.txt", "r", stdin);
string input;
string solution;
int line_counter = 0;
while(cin >> solution){
cin >> input;
Stack<char> stack;
string result;
//The input file is in the format "expected_solution infix_expression",
//where expected_solution is the infix_expression in postfix format
for(int i=0; i<input.length(); ++i){
// WRITE CODE HERE to store in 'result' the postfix transformation of 'input'
}
// You need to do some extra stuff here to store in 'result' the postfix transformation of 'input'
// Checking whether the result you got is correct
if(solution == result){
cout << "line " << line_counter << ": OK [" << solution << " " << result << "]" << endl;
}else{
cout << "line " << line_counter << ": ERROR [" << solution << " " << result << "]" << endl;
}
line_counter++;
}
}
Implement a stack and solutions to the following problems: balancing parenthesis, evaluating postfix expressions and transforming infix expressions into postfix expressions.
infix2postfix.cpp
- create main method to transform an infix expression into postfix
INFIX2POSTFIX.CPP #include "stack.hpp" using namespace std; // Auxiliary method, you probably find it useful // Operands are all lower case and upper case characters bool isOperand(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } // Auxiliary method, you probably find it useful int precedence(char c) { if(c == '+' || c == '-') { return 0; } if(c == '*' || c == '/') { return 1; } if(c == '^') { return 2; } return -1; } int main() { freopen("input_infix2postfix.txt", "r", stdin); string input; string output; //output string string solution; string dummy; string here; int j = 0; int con; int line_counter = 0; while(cin >> solution) { cin >> input; Stack<char> stack; string result; //The input file is in the format "expected_solution infix_expression", //where expected_solution is the infix_expression in postfix format int x = 0; for(int i=0; i<input.length(); ++i) { if (isOperand(input[i]) ) { output[j++] = input[i]; cout << "output: " << output[i] << endl; } else if (input[i] == '(' ) { stack.push(input[i]); } else if (input[i] == ')' ) { while (stack.peek() != '(' ) { output[j++] = stack.peek(); stack.pop(); } stack.pop(); } else if (input[i] == '*' || input[i] == '/' || input[i] == '+' || input[i] == '-' || input[i] == '^') { stack.push(input[i]); // cout << "input: " << stack.peek() << endl; if (precedence(stack.peek()) >= precedence(input[i]) ) { output[j++] = stack.peek(); stack.pop(); } else { break; } } }