As my homework I have to write a program that calculates an equation given as string. A part of the program is a function parsing an infix expression into postfix. Here is my code:
void dijkstra(string& s)
{
int i,j=s.size();
stack < char > znaki;
string output=" ";
string znak;
for(i=0; i<j;++i)
{
if((int(s[i])>47&&int(s[i])<58)||s[i]=='.')
{
output+=s[i];
}
else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
{
output+=" ";
if(znaki.empty())
{
}
else
{
if((s[i]=='+'||s[i]=='-'))
{
znak=znaki.top();
znaki.pop();
output+=znak;
}
else if(s[i]=='*')
{
if(znaki.top()=='*'||znaki.top()=='/')
{
znak=znaki.top();
znaki.pop();
output+=znak;
}
}
else if(s[i]=='/')
{
if(znaki.top()=='*'||znaki.top()=='/')
{
znak=znaki.top();
znaki.pop();
output+=znak;
}
}
}
znaki.push(s[i]);
}
else if(int(s[i])=='(')
{
znaki.push(s[i]);
}
else if(int(s[i])==')')
{
while(znaki.top()!='(')
{
output+=znaki.top();
znaki.pop();
}
znaki.pop();
}
}
while(znaki.empty()!=true)
{
output+=znaki.top();
znaki.pop();
}
s=output;
}
The problem is that it works in all conditions except equations like 4/6. Any ideas? I've just made requested updates
Related
I wrote a c++ code to convert infix expression to postfix expression using stacks but whenever I try to return the popped value from the stack,it's not returning the string.The returned string is null instead of the original content of the stack.
Do I need to convert it into char first?strong text
input: A+B
output: AB
correct output: AB+
How to return string from member function in c++?
#include<bits/stdc++.h>
using namespace std;
#define MAX 1000
int top=-1;
string stck[MAX];
void push(char data)
{
top++;
*(stck+top)=data;
}
string pop()
{
if(top<0)
{
return "";
}
else
{
top--;
return (*(stck+top));
}
}
bool isstckempty()
{
if(top==-1){
return true;
}
else
return false;
}
int main()
{
string s;
cin>>s;
string ss="";
int len=s.length();
int j=0;
for(int i=0;i<len;i++)
{
if(isalpha(s[i]))
{
ss=ss+s[i];
}
else
{
if(s[i]=='(')
{
push(s[i]);
}
else if(s[i]==')')
{
j=i-1;
while((s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
ss=ss+pop();
}
else if(s[i]=='+'||s[i]=='-')
{
j=i-1;
while((isstckempty()||s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
push(s[i]);
}
else if(s[i]=='*')
{
j=i-1;
while((isstckempty()||s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
push(s[i]);
}
else if(s[i]=='*')
{
j=i-1;
while((isstckempty()||s[j]!='(')&&(j>0))
{
ss=ss+pop();
j--;
}
push(s[i]);
}
}
}
while(!isstckempty){
ss=ss+pop();
}
cout<<ss<<endl;
return 0;
}
Your function pop() returns invalid data when top==0, because you decrement top before indexing the stack, and any array access with a negative index will be undefined. As others have said, don't implement your own stack, use std::stack and more obvious api's.
I'm trying to write a simple program to convert infix notation to prefix and postfix. So far the postfix one works perfectly. However, I can't seem to get the prefix conversion right. I used the shunting yard algorithm for both. Apologies beforehand if my code is a bit unusual (i.e. writing my own stack class instead of using #include, unnecessarily using other things), I have to meet assignment requirements (this is a college assignment). Here's what I've tried so far:
#include<iostream>
#include<string.h>
using namespace std;
const int Max=255;
class Stack
{
private:
char element[Max];
int top;
public:
Stack()
{
top=-1;
}
bool isFull()
{
if(top>=(Max-1)) return true;
else return false;
}
bool isEmpty()
{
if(top==-1) return true;
else return false;
}
bool push(char x)
{
if(!isFull())
{
top++;
element[top]=x;
return true;
}
else
{
cout<<"Stack is full"<<endl;
return false;
}
}
bool pop(char &x)
{
if(!isEmpty())
{
x=element[top--];
return true;
}
else
{
//cout<<"Stack is empty"<<endl;
return false;
}
}
char retrieve()
{
if(!isEmpty())
{
return element[top];
}
else
{
//cout<<"Stack is empty"<<endl;
return ' ';
}
}
};
class Converter
{
private:
public:
Converter(){}
bool isOperator(char x)
{
if(x=='+'||x=='-'||x=='*'||x=='/'||x=='^'||x=='('||x==')') return true;
else return false;
}
bool isOperand(char x)
{
if(x>='0'&&x<='9') return true;
else return false;
}
int Hierarchy(char x)
{
if(x=='+'||x=='-') return 1;
else if(x=='*'||x=='/') return 2;
else if(x=='^') return 3;
else return 0;
}
char*ToPostfix(char infix[])
{
Stack stack1;
char res[20];
int resindex=0;
for(int i=0;i<strlen(infix);i++)
{
if(isOperator(infix[i]))
{
if(infix[i]=='(')
{
stack1.push(infix[i]);
}
else if(infix[i]==')')
{
while(stack1.retrieve()!='(')
{
stack1.pop(res[resindex++]);
}
stack1.pop(res[resindex]);
}
else
{
while(Hierarchy(infix[i])<=Hierarchy(stack1.retrieve()))
{
stack1.pop(res[resindex++]);
}
stack1.push(infix[i]);
}
}
else if(isOperand(infix[i]))
{
res[resindex++]=infix[i];
}
}
while(!stack1.isEmpty())
{
stack1.pop(res[resindex++]);
}
res[resindex]='\0';
return res;
}
char*ToPrefix(char infix[])
{
char res[20];
strcpy(res,strrev(infix));
for(int i=0;i<strlen(res);i++)
{
if(res[i]=='(')
{
res[i]=')';
}
else if(res[i]==')')
{
res[i]='(';
}
}
strcpy(res,ToPostfix(res));
strcpy(res,strrev(res));
return res;
}
};
int main()
{
Converter convert;
char infix[20];
cout<<"Enter infix expression: ";
cin>>infix;
cout<<endl<<"Prefix: "<<convert.ToPrefix(infix)<<endl;
cout<<"Postfix: "<<convert.ToPostfix(infix)<<endl;
return 0;
}
when I try to convert a simple infix notation, i.e. 1*(2+3)/4^5-6, the postfix conversion is right (123+*45^/6-) but the prefix conversion returns the wrong answer (-*1/+23^456) instead of -/*1+23^456. can anyone help?
Actually, both answers are correct because you can switch the order of the division and the multiplication if multiplication comes first in infix. So your wrong answer is correct in this case. However, there is a left to right precedence, so your hierarchy handling is not correct: change else if(x=='*'||x=='/') return 2;.
I could use help with solving this problem, looked online and saw that many problems were due to the size of the array in other programmer's programs. So I tried changing numbers affecting the array "sub" and still haven't found a solution. All instances of sub in my program are included below.
int sub[9]={0,0,0,0,0,0,0,0,0};
for(int i=0;i<=8;i++)
{
if(sub[i]>0)
{
if(one==sub[i]&one>0&one<200)
{
cout<<"\t\tP1";
}
if(two==sub[i]&two>0&two<200)
{
cout<<"\t\tP2";
}
if(three==sub[i]&three>0&three<200)
{
cout<<"\t\tP3";
}
if(four==sub[i]&four>0&four<200)
{
cout<<"\t\tP4";
}
if(five==sub[i]&five>0&five<200)
{
cout<<"\t\tP5";
}
if(six==sub[i]&six>0&six<200)
{
cout<<"\t\tP6";
}
if(seven==sub[i]&seven>0&seven<200)
{
cout<<"\t\tP7";
}
if(eieght==sub[i]&eieght>0&eieght<200)
{
cout<<"\t\tP8";
}
if(nine==sub[i]&nine>0&nine<200)
{
cout<<"\t\tP9";
}
cout<<"\t\t"<<sub[i]<<"\n\n";
}
}
for(int i=0;i<=8;i++)
{
if(one==sub[i])
{
one=one-cut;
}
if(two==sub[i])
{
two=two-cut;
}
if(three==sub[i])
{
three=three-cut;
}
if(four==sub[i])
{
four=four-cut;
}
if(five==sub[i])
{
five=five-cut;
}
if(six==sub[i])
{
six=six-cut;
}
if(seven==sub[i])
{
seven=seven-cut;
}
if(eieght==sub[i])
{
eieght=eieght-cut;
}
if(nine==sub[i])
{
nine=nine-cut;
}
}
for(int i=0;i<=8;i++)
{
sub[i]= sub[i]-cut;
}
for(int i=0;i<=8;i++)
{
if(sub[i]<=0)
{
sub[i]=sub[i+1];
sub[i+1]=0;
}
}
if(sub[0]<=0)
{
sub[0]=IO;
}
else if(sub[1]<=0)
{
sub[1]=IO;
}
else if(sub[2]<=0)
{
sub[2]=IO;
}
else if(sub[3]<=0)
{
sub[3]=IO;
}
You are accessing outside your array here:
for(int i=0;i<=8;i++)
{
if(sub[i]<=0)
{
sub[i]=sub[i+1]; //^^if i =8, then i +1 = 9, array index out of bound
sub[i+1]=0; //^^same as above
}
}
How can we append the two string in bb10???
I m to make a calculator for blackberry but get some errors.
Please help me out.
I got error in this code:
void CalcTrial::oneButtonClicked()
{
// Change the button text when clicked
if(textf==NULL)
{
textf->setText("1");
}
else
{
textf->QString+"1";
}
}
void CalcTrial::twoButtonClicked()
{
if(textf==NULL)
{
textf->setText("2");
}
else
{
textf->QString+"2";
}
}
void CalcTrial::threeButtonClicked()
{
if(textf==NULL)
{
textf->setText("3");
}
else
{
textf->QString+"3";
}
}
void CalcTrial::fourButtonClicked()
{
if(textf==NULL)
{
textf->setText("4");
}
else
{
textf->QString+"4";
}
}
void CalcTrial::fiveButtonClicked()
{
if(textf==NULL)
{
textf->setText("5");
}
else
{
textf->QString+"5";
}
}
void CalcTrial::sixButtonClicked()
{
if(textf==NULL)
{
textf->setText("6");
}
else
{
textf->QString+"6";
}
}
void CalcTrial::sevenButtonClicked()
{
if(textf==NULL)
{
textf->setText("7");
}
else
{
textf->QString+"7";
}
}
void CalcTrial::eightButtonClicked()
{
if(textf==NULL)
{
textf->setText("8");
}
else
{
textf->QString+"8";
}
}
void CalcTrial::nineButtonClicked()
{
if(textf==NULL)
{
textf->setText("9");
}
else
{
textf->QString+"9";
}
}
void CalcTrial::zeroButtonClicked()
{
if(textf==NULL)
{
textf->setText("0");
}
else
{
textf->QString+"0";
}
}
void CalcTrial::addButtonClicked()
{
operation=1;
temp1 = QString(getchar())+textf;
textf->setText(NULL);
}
void CalcTrial::minusButtonClicked()
{
operation=2;
temp1 = QString(getchar())+textf;
textf->setText(NULL);
}
void CalcTrial::mulButtonClicked()
{
operation=3;
temp1 = QString(getchar())+textf;
textf->setText(NULL);
}
void CalcTrial::divButtonClicked()
{
operation=4;
temp1 = QString(getchar())+textf;
textf->setText(NULL);
}
void CalcTrial::equalButtonClicked()
{
temp2 = QString(getchar())+temp1;
switch (operation) {
case 1:
result=temp1+temp2;
break;
case 2:
result=temp1-temp2;
break;
case 3:
result=temp1*temp2;
break;
case 4:
result=temp1/temp2;
break;
default:
break;
}
textf->text(result);
}
To convert QString to an int:
QString strNum = "22";
int intNum = strNum.toInt();
I'm trying to Parse a Fully Parenthesized Exp for this grammar:
exp->(exp + exp)
|(exp - exp)
| num
num->[0-9]
...but I have a problem: when I enter "1+4" no error appears. How can I solve it ??
This is a classic problem of recursive descent parsers: your grammar does not require that the entire input is consumed. Once it finishes with the "while isdigit" loop, it considers its job done, ignoring the +4 portion of the input.
Add a check that the end of line is reached after the call of the top-level expression to address this problem:
void TopExp() {
Expr();
Match('\n');
}
You need to modify Match to allow matching \n when no additional input is available:
void Match(char c) {
int p = cin.peek();
if(p==c) {
cin>>c;
} else if (p == EOF && c == '\n') {
return
} else {
cout<<"Syntax Error! "<<(char)cin.peek()<<endl;
cin.ignore();
}
}
Try with this changed instruction: if (openParenthesis-closeParenthesis>0)
int Match(char c)
{
if(cin.peek()==c) {
cin>>c;
return 1;
} else
{
cout<<"Syntax Error! "<<(char)cin.peek()<<endl;
cin.ignore();
return 0;
}
}
void MatchOp()
{
if(cin.peek()=='+')
Match('+');
else if(cin.peek()=='-')
Match('-');
else
{
cout<<"invalid Operation: "<<(char)cin.peek()<<endl;
cin.ignore();
}
}
void Exp()
{ static int openParenthesis = 0;
static int closeParenthesis = 0;
if(cin.peek()!='\n')
if(cin.peek()=='(')
{
if (Match('(') == 1) {
openParenthesis += 1;
}
Exp();MatchOp();Exp();
if (Match(')') == 1) {
closeParenthesis -= 1;
}
}
else if(isdigit(cin.peek()))
{
if (openParenthesis-closeParenthesis>0) {
cout<<"Syntax Error! "<<(char)cin.peek()<<endl;
cin.ignore();
} else {
while(isdigit(cin.peek()))
{ cout<<(char)cin.peek();
Match(cin.peek());
}
}
}
else
{
cout<<"Syntax Error!"<<(char)cin.peek()<<endl;
cin.ignore();
}
}