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();
}
}
Related
I am trying to make a program that converts a number written in words to numbers.. (e.g in(sixty-four) -> out(64)) with some exceptions of course. well I struggle in this part of code. I don't know what to put as a return value..
int tys(string x) {
int a=0,n,i;
string sum;
for (auto &c: x) {
if (isalpha(c)) c=tolower(c);
for (i=0;i<x.size()+1;++i) {
if (x[i]=='-') {
for (a=i-2;a<i;++a) {
sum += x[a];
if (sum=="ty") {
i=i-3;
for (a=0;a<i;++a) sum+=x[a];
n=first_digits(sum)*10;
sum=' ';
a=i+4;
while (a<x.size()) {
++a;
sum+=x[a];
if (a==x.size()) {
n+=first_digits(sum);
return n;
}
}
}
}
}
else if (i==x.size()){
for (a=i-1;a<i+1;++a) {
sum += x[a];
if (sum=="ty") {
sum=' ';
while (a <x.size()-3) {
++a;
sum += x[a];
if (a==x.size()-3) {
n = first_digits(sum) * 10;
return n;
}
}
}
}
}
}
}
return true;
}
don't mind the first_digits because it's an int function that works already which gives the numbers from 0-20
I am making a move function for a game and I get a expected expression error I can't figure out why, it seems legal what i did.
void Ant::move()
{
int dir=rand()%4;
if (dir==0)
{
if ((y>0) && (world->getAt(x,y-1)==NULL))
{
world->setAt(x,y-1,world->getAt(x,y));
world->setAt(x,y,NULL);
y++;
}
}
else
{
if ((x<WORLDSIZE-1) && (world->getAt(x+1,y)==NULL))
{
world->setAt(x-1,y,world->getAt(x,y));
world->setAt(x,y,NULL);
x--;
}
}
else
{
if ((x<WORLDSIZE-1) && (world-getAt(x+1,y)==NULL))
{
world->setAt(x+1,y,world->getAt(x,y));
world->setAt(x,y,NULL);
x++;
}
}
}
The problem is the second else call.
I think the problem is:
world-getAt(x+1,y)==NULL
You forgot the >
world->getAt(x+1,y)==NULL
In the second if statement.
There is an if missing after the first else. You have now
if {
...
} else { // here you need an if - or revise the structure
} else {
}
For instance try ...
void Ant::move()
{
int dir=rand()%4;
if (dir==0)
{
if ((y>0) && (world->getAt(x,y-1)==NULL))
{
world->setAt(x,y-1,world->getAt(x,y));
world->setAt(x,y,NULL);
y++;
} else
if ((x<WORLDSIZE-1) && (world->getAt(x+1,y)==NULL))
{
world->setAt(x-1,y,world->getAt(x,y));
world->setAt(x,y,NULL);
x--;
} else
if ((x<WORLDSIZE-1) && (world-getAt(x+1,y)==NULL))
{
world->setAt(x+1,y,world->getAt(x,y));
world->setAt(x,y,NULL);
x++;
}
}
}
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
Here i have a code for converting Infix To Postfix using Stack
the code compiled without errors but my problem is When I enter any infix e.g A+B i got a postfix of AB without the operators or parenthesis i couldn't solve this problem and i have an exam tomorrow please save me and tell me What i am missing here and thanks a lot.....
#include <iostream>
#include <string.h>
using namespace std;
struct stack
{
int ptr;
char arr[50];
stack()
{
ptr=0;
}
char top()
{
return arr[ptr];
}
void push(char ch)
{
ptr++;
arr[ptr]=ch;
}
void pop()
{
ptr-- ;
}
};
void Convert(char[50],char[50]);
bool IsOperand(char);
bool TakesPrecedence(char,char);
void main()
{
char Reply;
do
{
char Infix[50],Postfix[50]="";
cout<<"Enter an Infix expression: "<<endl;
cin>>Infix;
Convert(Infix,Postfix);
cout<<"The equivalent postfix expression is: "<<endl<<Postfix<<endl;
cout<<endl<<"Do another (y/n)? ";
cin>>Reply;
}
while (Reply =='y');
}
void Convert(char Infix[50],char Postfix[50])
{
stack OperatorStack;
char TopSymbol,Symbol;
int L;
for(unsigned k=0;k<strlen(Infix);k++)
{
Symbol=Infix[k];
if (IsOperand(Symbol))
{
L=strlen(Postfix);
Postfix[L]=Symbol;
Postfix[L+1]='\0';
}
else
{
while ( OperatorStack.ptr && TakesPrecedence(OperatorStack.top(),Symbol))
{
TopSymbol= OperatorStack.top();
OperatorStack.pop();
L=strlen(Postfix);
Postfix[L]=TopSymbol;
Postfix[L+1]='\0';
}
if( OperatorStack.ptr && Symbol==')')
OperatorStack.pop();
else
OperatorStack.push(Symbol);
}
}
while(OperatorStack.ptr)
{
TopSymbol=OperatorStack.top();
OperatorStack.pop();
L=strlen(Postfix);
Postfix[L+1]='\0';
}
}
bool IsOperand(char ch)
{
if((ch >='a' &&ch <= 'z') ||(ch >='A' &&ch <= 'Z')||(ch >='0' &&ch <= '9'))
return true;
else
return false;
}
bool TakesPrecedence(char OperatorA,char OperatorB)
{
if(OperatorA='(')
return false;
else if(OperatorB='(')
return false;
else if(OperatorB=')')
return true;
else if(OperatorA='^' && (OperatorB='^'))
return false;
else if(OperatorA='^')
return true;
else if(OperatorB='^')
return false;
else if(OperatorA='*' || (OperatorA='/'))
return true;
else if(OperatorB='*' || (OperatorB='/'))
return false;
else
return true;
}
Pretty sure
if(OperatorA='(')
and all other should be
if(OperatorA=='(')
But my main advice is for you to start using a debugger. This could have easily been spotted during debugging. I can't stress enough how important knowing how to debug is.
I can't use boost::spirit in my environment. But I would like to use STL and boost as much as possible to build my own expression evaluator. Is there such an alternative to boost::spirit?
The following code includes unit tests and a complete parser I wrote in an about 90 minute session at ACCU 200x (8 or 9). If you need more, it might be easy enough to extend. You can make it do doubles by defining Parse::value_type, or extracting it into a separate header file and make it a template class.
Or you can take the test cases and try yourself. (it uses CUTE from http://cute-test.com)
#include "cute.h"
#include "ide_listener.h"
#include "cute_runner.h"
#include <cctype>
#include <map>
namespace {
class Parser {
typedef int value_type;
typedef std::vector<value_type> valuestack;
typedef std::vector<char> opstack;
typedef std::map<std::string,value_type> memory;
public:
memory variables;
private:
void evaluateSingleOperator(char op,value_type &result,value_type operand) {
switch(op) {
case '+': result += operand; break;
case '-': result -= operand; break;
case '*': result *= operand; break;
case '/': result /= operand; break;
default: throw("invalid operand");
}
}
void evaluateStacks(valuestack &values, opstack &ops) {
while(ops.size() && values.size()>1) {
char op = ops.back(); ops.pop_back();
value_type operand = values.back(); values.pop_back();
evaluateSingleOperator(op,values.back(),operand);
}
}
bool higherPrecedenceOrLeftAssociative(char last, char current) {
return (last == current)||(last == '*' || last == '/') ;
}
bool shouldEvaluate(char op,opstack const &ops) {
return ops.size() > 0 && higherPrecedenceOrLeftAssociative(ops.back(),op);
}
std::string parseVariableName(std::istream &is) {
std::string variable;
char nextchar=0;
while ((is >> nextchar) && isalpha(nextchar)) {
variable += nextchar;
}
if (variable.size() == 0) throw std::string("internal parse error");
is.unget();
return variable;
}
int peekWithSkipWhiteSpace(std::istream &is) {
int nextchar = EOF;
while(isspace(nextchar = is.peek())) is.get();
return nextchar;
}
value_type getOperand(std::istream &is) {
int nextchar = peekWithSkipWhiteSpace(is);
if (nextchar == EOF) throw std::string("syntax error operand expected");
if (isdigit(nextchar)){
value_type operand=0;
if (!(is >> operand)) throw std::string("syntax error getting number") ;
return operand;
} else if ('(' == nextchar) {
is.get();
return parse(is);
} else if (isalpha(nextchar)) {
std::string variable= parseVariableName(is);
if( parseAssignmentOperator(is)) {
variables[variable] = parse(is);
} else {
if (!variables.count(variable)) throw std::string("undefined variable: ")+variable;
}
return variables[variable];
}
throw std::string("syntax error");
}
bool parseAssignmentOperator(std::istream &is) {
int nextchar = peekWithSkipWhiteSpace(is);
if ('=' != nextchar) {
return false;
}
is.get();
return true;
}
public:
value_type parse(std::istream &is) {
is >> std::skipws;
valuestack values;
opstack ops;
values.push_back(getOperand(is));
char op=')';
while((is >>op) && op != ')') {
if (shouldEvaluate(op, ops)) {
evaluateStacks(values, ops);
}
values.push_back(getOperand(is));
ops.push_back(op);
}
evaluateStacks(values,ops);
return values.back();
}
value_type eval(std::string s) {
std::istringstream is(s);
return parse(is);
}
};
int eval(std::string s) {
return Parser().eval(s);
}
void shouldThrowEmptyExpression() {
eval("");
}
void shouldThrowSyntaxError() {
eval("()");
}
void testSimpleNumber() {
ASSERT_EQUAL(5,eval("5"));
}
void testSimpleAdd() {
ASSERT_EQUAL(10,eval("5 +5"));
}
void testMultiAdd() {
ASSERT_EQUAL(10,eval("1 + 2 + 3+4"));
}
void testSimpleSubtract() {
ASSERT_EQUAL(5,eval("6-1"));
}
void testTenPlus12Minus100() {
ASSERT_EQUAL(-78,eval("10+12-100"));
}
void testMultiply() {
ASSERT_EQUAL(50,eval("10*5"));
}
void testDivision() {
ASSERT_EQUAL(7,eval("21/3"));
}
void testAddThenMultiply() {
ASSERT_EQUAL(21,eval("1+4 *5"));
}
void testAddThenMultiplyAdd() {
ASSERT_EQUAL(16,eval("1+4*5 -5"));
}
void testAddSubSub() {
ASSERT_EQUAL(-4,eval("1+2-3-4"));
}
void testSimpleParenthesis() {
ASSERT_EQUAL(1,eval("(1)"));
}
void testSimpleOperandParenthesis() {
ASSERT_EQUAL(2,eval("1+(1)"));
}
void testParenthesis() {
ASSERT_EQUAL(5,eval("2*(1+4)-5"));
}
void testNestedParenthesis() {
ASSERT_EQUAL(16,eval("2*(1+(4*3)-5)"));
}
void testDeeplyNestedParenthesis() {
ASSERT_EQUAL(8,eval("((2*((1+(4*3)-5)))/2)"));
}
void testSimpleAssignment() {
Parser p;
ASSERT_EQUAL(1, p.eval("a=1*(2-1)"));
ASSERT_EQUAL(8, p.eval("a+7"));
ASSERT_EQUAL(1, p.eval("2-a"));
}
void testLongerVariables() {
Parser p;
ASSERT_EQUAL(1, p.eval("aLongVariableName=1*(2-1)"));
ASSERT_EQUAL(42, p.eval("AnotherVariable=7*(4+2)"));
ASSERT_EQUAL(1, p.eval("2-(aLongVariableName*AnotherVariable)/42"));
}
void shouldThrowUndefined() {
eval("2 * undefinedVariable");
}
void runSuite(){
cute::suite s;
//TODO add your test here
s.push_back(CUTE_EXPECT(CUTE(shouldThrowEmptyExpression),std::string));
s.push_back(CUTE_EXPECT(CUTE(shouldThrowSyntaxError),std::string));
s.push_back(CUTE(testSimpleNumber));
s.push_back(CUTE(testSimpleAdd));
s.push_back(CUTE(testMultiAdd));
s.push_back(CUTE(testSimpleSubtract));
s.push_back(CUTE(testTenPlus12Minus100));
s.push_back(CUTE(testMultiply));
s.push_back(CUTE(testDivision));
s.push_back(CUTE(testAddThenMultiply));
s.push_back(CUTE(testAddSubSub));
s.push_back(CUTE(testAddThenMultiplyAdd));
s.push_back(CUTE(testSimpleParenthesis));
s.push_back(CUTE(testSimpleOperandParenthesis));
s.push_back(CUTE(testParenthesis));
s.push_back(CUTE(testNestedParenthesis));
s.push_back(CUTE(testDeeplyNestedParenthesis));
s.push_back(CUTE(testSimpleAssignment));
s.push_back(CUTE(testLongerVariables));
s.push_back(CUTE_EXPECT(CUTE(shouldThrowUndefined),std::string));
cute::ide_listener lis;
cute::makeRunner(lis)(s, "The Suite");
}
}
int main(){
runSuite();
}
YACC++ is a very good tool for parser generator for c++ applications. ANTLR is also agood option howver that does not have good documentation for its usage in C/C++.