C++ infix to postfix - c++

I get the following error when I compile:
convert.cpp: In function 'std::string convert()':
convert.cpp:62: error: expected primary-expression before 'else'
convert.cpp:62: error: expected `;' before 'else'
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
convert.cpp:108: error: expected `}' at end of input
Code:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
string infix; // infix expression string
string operand;
string operate;
stack <string> mystack; // this stack is used to push the operator
string postfix; // postfix string where the operand is appended
//....................................................................
// this function read the infix expression from user
string input()
{
cout<<" Enter the damn infix expression: "<<endl;
getline(cin, infix);
return infix;
}
//......................................................................
// this function checks for operator precedence in the stack
int precedence(string e)
{
int f;
if(e == "*" || e== "/" || e =="%")
f = 2;
else
{
if(e == "+" || e == "-")
f = 1;
}
if(e=="."){
f=0;
}
return f;
}
//....................................................................
// This function converts infix to postfix
string convert()
{
for(int i=0; i<infix.length(); i++)
{
switch(infix[i]){
// operate case start
case '+': case'-': case'*': case'/': case'^': case '(': case ')': case'.':
operate=infix[i];
{
if(mystack.empty() || precedence(operate)>= precedence(mystack.top()))
{
mystack.push(operate);
else
{
while(precedence(operate)<= precedence(mystack.top()))
{
postfix.append(mystack.top());
mystack.pop();
}
mystack.push(operate);
}
}
}//operate case closed
default: //when operand string char is parsed
{
operand=infix[i];
postfix.append(operand);
break;
} // default case closed
}//switch closed
}
while(!mystack.empty())
{
postfix.append(mystack.top())
mystack.pop();
}
return postfix;
cout<<postfix;
}
//...................................................................
int main()
{
input();
convert();
cout<<"postfix is "<<postfix<<endl;
}

It appears that your code is just missing some closing braces. That's all.
For example, look at this:
operate=infix[i];
{
if(mystack.empty() || precedence(operate)>= precedence(mystack.top()))
{
mystack.push(operate);
else
{
while(precedence(operate)<= precedence(mystack.top()))
Where is the closing } before the else statement. Just go through your code and fix these silly mistakes.
It would be a lot easier to rid yourself of these things if you made your spacing and indentation a little neater.

The "expected primary expression before else" diagnostic is the compiler-author's way of reporting you rudely foisted on him an "else" without either a preceding "if" or (what amounts to the same thing) "else if". Alexander Rafferty correctly points out that this is because the code has ...
if (condition) {
// ...
else { }
... when perhaps what you meant was ...
if (condition) {
// ...
}
else {
}
... though maybe you deleted a whole bunch of stuff by accident, and were lucky enough that the deletion resulted in unparseable code, so you will realize that something is wrong.

Look at these lines:
if(mystack.empty() || precedence(operate)>= precedence(mystack.top()))
{
mystack.push(operate);
else

Related

Infix to Postfix Stack C++ Output

#include<iostream>
#include<cstring>
#include<string>
#include "linkedStack.h"
#include <fstream>
#include <iomanip>
#include "ArgumentManager.h"
using namespace std;
int getPrecedence(char ch) //this function will decide and return precedence for the operators and operand
{
switch (ch)
{
case '/':return 2;
break;
case '*': return 2;
break;
case '+': return 1;
break;
case '-': return 1;
break;
default: return 0;
}
}
string infixToPostfix(const string& expression) // this function will convert the infix expression to postfix by passing the infix expression string
{
int size = expression.size(); //size of infix string
char infix[expression.size()]; //converting string into array of chars
strncpy(infix, expression.c_str(), sizeof(infix));
infix[sizeof(infix)] = '\0'; //adding 0 for array ending
char postfix[strlen(infix)]; // create a char array with the size of the infix string length
linkedStack s;
int precedence;
int i = 0;
int k = 0;
char ch;
//iterate the infix expression
while (i < size)
{
ch = infix[i];
//push opening parenthesis to stack
if (ch == '(')
{
s.push(ch);
i++;
continue;
}
if (ch == ')')
{
while (!s.empty() && s.top() != '(') // if closing parenthesis is found pop of all the elements and append it to the postfix expression till we encounter an opening parenthesis
{
postfix[k++] = s.top();
s.pop();
}
if (!s.empty())
{
s.pop(); // pop the opening parenthesis
}
i++;
continue;
}
precedence = getPrecedence(ch);
if (precedence == 0)
{
postfix[k++] = ch; // if an operand is found add it to the postfix expression
}
else
{
if (s.empty())
{
s.push(ch); //push operator onto stack if the stack is empty
}
else
{
while (!s.empty() && s.top() != '(' && precedence <= getPrecedence(s.top())) // pop of all the operators from the stack to the postfix expression till we see an operator with a lower precedence than the current operator
{
postfix[k++] = s.top();
s.pop();
}
s.push(ch); // push the current operator to stack
}
}
i++;
}
while (!s.empty()) // pop all of the the remaining operators in the stack and add it to postfix
{
postfix[k++] = s.top();
s.pop();
}
postfix[k] = '\0'; // add null character to end of character array for c string
string postfixStr = postfix; //covert the final postfix char array to a string
return postfixStr; // returns the final postfix expression as a string
}
int main(int argc, char* argv[])
{
ArgumentManager am(argc, argv);
string infilename = am.get("A");
string outfilename = am.get("C");
string expression1;
ifstream infile;
infile.open(infilename);
if (infile.good())
{
getline(infile, expression1); //gets the infix string from file
}
infile.close(); //close the infile stream
string expression2 = "12 + 3 / 4";
string postfix1 = infixToPostfix(expression1);
string postfix2 = infixToPostfix(expression2);
cout << expression1 << endl;
cout << postfix1 << endl;
cout << expression2 << endl;
cout << postfix2 << endl;
return 0;
}
Hi, I'm having trouble with my output with my infix to post fix converter using stack. For instance in the case of "12 + 3 / 4" the output should be "12 3 4 / +" with the characters evenly spaced by one white space. However, it is adding unnecessary white spaces or none at all. For the test case above you can see the problem I'm running into in the attached pic or below. The first line is the infix the second is the post fix output. There are two cases here.Output Example
25 + ( 4 * 5 ) - 12
25 4 5 * + 12-
12 + 3 / 4
12 3 4/+
1) This code :
int size = expression.size(); //size of infix string
char infix[expression.size()]; //converting string into array of chars
strncpy(infix, expression.c_str(), sizeof(infix));
infix[sizeof(infix)] = '\0'; //adding 0 for array ending
could be replaced by :
char * infix = new char [expression.length()+1];
std::strcpy (infix, expression.c_str());
2) This code pop values without repush them into s after.
while (!s.empty() && s.top() != '(' && precedence <= getPrecedence(s.top())) // pop of all the operators from the stack to the postfix expression till we see an operator with a lower precedence than the current operator
{
postfix[k++] = s.top();
s.pop();
}
Thanks for all the advice. In the end I did a few things to achieve the desired output. First, I increased the postfix array. Next, in two certain spots in the loop, whenever it appended to the postfix array I would also add a space.
Here:
while (!s.empty() && s.top() != '(' && precedence <= getPrecedence(s.top())) // pop of all the operators from the stack to the postfix expression till we see an operator with a lower precedence than the current operator
{
postfix[k++] = s.top();
postfix[k++] = ' ';
s.pop();
}
And here:
while (!s.empty()) // pop all of the the remaining operators in the stack and add it to postfix
{
postfix[k++] = s.top();
postfix[k++] = ' ';
s.pop();
}
Lastly, I used a separate function to trim any extra spaces in the final string.
A little messy but gets the job done.

Error passing strings and char to bool function

I am trying to create a function that looks at a '-' sign and checks whether is a minus sign or a negative sign based on if it has a ' ' (space) in front of it. I am doing so by comparing the current char I have (infix[x]) and comparing to infix[x+1]; I keep getting error but im unsure if its because im not passing correctly or something else?
for(unsigned x = 0; x < infix.length(); ++x)
{
// place numbers (standard, decimal, & negative)
// numbers onto the 'postfix' string
if((isdigit(infix[x])) || (infix[x] == '.'))
{
postfix += infix[x];
}
else if ((infix[x] == '-'))
{
if(checkfornegative(infix[x], infix)== 1)) // error: expected primary-expression before ‘)’ token
if(checkfornegative(infix[x], infix)== 1))
{
postfix+= " ";
}
else if(checkfornegative(infix[x], infix)== 0)) //error: expected primary-expression before ‘)’ token
if(checkfornegative(infix[x], infix)== 1))
{
postfix += infix[x];
}
}
// This is the function in using
bool checkfornegative(char C, string& QQ)
{
bool status;
if((C == '-') && (QQ[C+1] == ' '))
{
status = true;
}
else if((C == '-') && (QQ[C+1] != ' '))
{
status = false;
}
return status;
}
You are getting compilation errors because you have extra closing parenthesis in the if conditions.
if(checkfornegative(infix[x], infix)== 1)) // error: expected primary-expression before ‘)’ token
Remove the last closing parenthesis from the condition. Same goes for the second condition also.
However, there are several issues in your code but they are not compilation errors.

Infix to postfix conversion (using stack)

I wrote a program to convert infix to postfix operation using stack in c++. But on running this I am getting Segmantation fault.
Please help me know my mistake. I am not able to know.
I have used the algorithm as below:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.
The code is :
#include<iostream>
#include<stack>
using namespace std;
int preceedence(char x) {
switch(x) {
case '+':
case '-':
return 1;
break;
case '*':
case '/':
return 2;
break;
case '^':
return 3;
break;
return -1;
}
}
// A utility function to check if the given character is operand
bool isOperand(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
int infixToPostfix(string str) {
stack<char> operators;
string output;
for(string::iterator it = str.begin(); it != str.end(); ++it) {
if(isOperand(*it)) {
output += *it;
cout << *it;
} else if(*it == '('){
operators.push(*it);
} else if(*it == ')') {
while(!operators.empty() && operators.top() != '(') {
output += operators.top();
operators.pop();
}
if(!operators.empty() && operators.top() != '(') {
cout << "Invalid Expression";
return -1;
} else {
operators.pop();
}
} else { // An operator is encountered.
while(!operators.empty()) {
if(preceedence(*it) <= preceedence(operators.top())) {
output += operators.top();
operators.pop();
} else {
break;
}
}
operators.push(*it);
}
}
while(!operators.empty()) {
output += operators.top();
operators.pop();
}
cout << output<< endl;
return 0;
}
int main() {
string str;
//getline(std::cin, str);
str = "(1+2)*5";
cout << "The postfix conversion of the infix stream is : "<< endl;
infixToPostfix(str);
return 0;
}

Closing Parenthesis Recognition and Precedence of Operators In Infix to Postfix Stack Program C++

I have an assignment in my Data Structures course where the C++ program calls a function named infixToPostfix, which reads an infix expression from standard input and writes the equivalent postfix expression to standard output.
However, I'm having difficulties with two logic errors at the moment:
My closing parenthesis isn't getting recognized in my program. When I attempt to pop the ')' out of the stack, it causes a segmentation error, crashing the program.
The precedence of operators during the conversion isn't in proper order. I'm guessing it's because my program is recognizing the operators to where each operator pops the previous one out of the stack, no matter what their precedence is.
My current code:
#include <iostream>
#include <stack> // Library used to store a stack of characters
#include <string>
using namespace std;
bool isOperator(char ch) // Checks if character is operator
{
if(ch == '^' || ch == '*' || ch == '/' || ch == '+' || ch == '-')
{
return true;
}
else
{
return false;
}
}
bool isOperand(char ch) // Checks if character is operand
{
// If not an operator or a parenthesis, then assume operand
if(!isOperator(ch) && ch != '(' && ch != ')')
{
return true;
}
else
{
return false;
}
}
// Retrieves weight of operators as per precedence
// Higher weight = higher precedence in operators
// Returns 0 for non-operators
int getWeight(char ch)
{
switch(ch) {
case '^': // exponents
return 3;
case '/':
case '*':
return 2;
case '+':
case '-':
return 1;
default :
return 0;
}
}
string infixToPostfix(string expression)
{
// Declare stack
stack<char> op_stack;
// Initialize postfix as empty string
string postfix = "";
for(int i = 0; i < expression.length(); i++)
{
// Scanning each character from left.
// If character is a delimiter, move on.
if(expression[i] == ' ' || expression[i] == ',')
{
continue;
}
// If character is operator, pop two elements from stack,
// perform operation, and push result back.
else if(isOperator(expression[i]))
{
while(!op_stack.empty() && op_stack.top() != \
getWeight(op_stack.top()) <= getWeight(expression[i]))
{
postfix += op_stack.top();
op_stack.pop();
}
op_stack.push(expression[i]);
}
// Else if character is operand
else if(isOperand(expression[i]))
{
postfix += expression[i];
}
// Parenthesis
else if(expression[i] == '(')
{
// Push operator onto stack if empty
op_stack.push(expression[i]);
}
else if(expression[i] == ')')
{
while(!op_stack.empty() && op_stack.top() != '(')
{
postfix += op_stack.top();
op_stack.pop();
}
//op_stack.pop();
}
}
while(!op_stack.empty())
{
postfix += op_stack.top();
op_stack.pop();
}
return postfix;
}
int main() {
string expression;
cout << "Enter Infix Expression: \n";
getline(cin, expression);
// Displays inputted infix string and calculated
// Postfix string
cout << "Infix Expression: " << expression << '\n';
cout << "Postfix Expression: " << infixToPostfix(expression) << '\n';
return 0;
}
Sample output:
Enter Infix Expression:
(6+2)*5^8/4
Infix Expression: (6+2)*5^8/4
Postfix Expression: 6(2+5*8^4/
Where the correct postfix should be 62+58^*4/
Any help would be greatly appreciated.

prefix calculator having trouble compilng

I am having some trouble with a program that is supposed to take a command line expression and interpret it as a normal mathematical expression.This is what I am getting as an error:
driver.cpp: In function ‘int main(int, char**)’:
driver.cpp:17:57: error: no matching function for call to‘PrefixCalculator::eval(std::istringstream)’
driver.cpp:17:57: note: candidate is:
PrefixCalculator.h:33:3: note: T PrefixCalculator::eval(std::istringstream&) [with T = int, std::istringstream = std::basic_istringstream]
PrefixCalculator.h:33:3: note: no known conversion for argument 1 from ‘std::istringstream {aka std::basic_istringstream}’ to ‘std::istringstream& {aka std::basic_istringstream&}’
I can't understand what the error is trying to suggest to me.
Any suggestions for fixing that? I'm going to add exceptions later, so they are commented out for now.
This is the code:
PrefixCalculator.cpp
#pragma once
#include <sstream>
using namespace std;
template<class T>
class PrefixCalculator {
public:
PrefixCalculator(void){
numOperator = 0;
numOperand = 0;
};
~PrefixCalculator(void){};
T eval(istringstream&);
int getNumOperator() {
return numOperator;
};
int getNumOperand() {
return numOperand;
};
private:
//if you feel you need private helper functions and/or helper data
int numOperator;
int numOperand;
};
template<class T>
T PrefixCalculator<T>::eval(istringstream& input) {
//this function needs to throw an exception if there's a problem with the expression or operators
char nextChar = input.peek();
//this while loop skips over the spaces in the expression, if there are any
while(nextChar == ' ') {
input.get(); //move past this space
nextChar = input.peek(); //check the next character
}
if(nextChar == '+') {
input.get(); //moves past the +
numOperator++;
return eval(input) + eval(input); //recursively calculates the first expression, and adds it to the second expression, returning the result
}
/***** more operators here ******/
if(nextChar == '-') {
input.get();
numOperator++;
return eval(input) - eval(input);
}
if(nextChar == '*') {
input.get();
numOperator++;
return eval(input) * eval(input);
}
if(nextChar == '/') {
input.get();
numOperator++;
return eval(input) / eval(input);
}
/****** BASE CASE HERE *******/
//it's not an operator, and it's not a space, so you must be reading an actual value (like '3' in "+ 3 6". Use the >> operator of istringstream to pull in a T value!
input>>nextChar;
T digit = nextChar - '0';
numOperand++;
return digit;
//OR...there's bad input, in which case the reading would fail and you should throw an exception
}
driver.cpp
#include <sstream>
#include <string>
#include <iostream>
#include "PrefixCalculator.h"
using namespace std;
int main(int argc, char** argv) {
PrefixCalculator<int> calc;
string expression;
cout << "Give a prefix expression to evaluate, or q to quit." << endl;
getline(cin,expression);
while(expression[0] != 'q') {
//try {
int result = calc.eval(istringstream(expression));
cout << result << endl;
//}
//catch { //will not compile, you have to finish this!
//
//}
cout << "Give a prefix expression to evaluate or q to quit." << endl;
getline(cin,expression);
}
return 0;
}
calc.eval(istringstream(expression)); passes a temporary instance to eval(), you'll need an lvalue.
Provide an extra variable for the stream
istringstream iss(expression);
and pass that one
int result = calc.eval(iss);