Skip to main content
gamedev.net
🔒 Locked 🤖 Godot

Yacc/Lex code problem

Started by CodeguruX Dec 15, 2005 at 7:32 PM 0 replies 2.3k views
Original Post
CodeguruX
CodeguruX
Lex file:

%{ 
   #include <stdlib.h>
   #include "y.tab.h"
   void yyerror(char *);
%}

VAR [a-z]
%%

{VAR} {yylval.value[0]=*yytext;
       yylval.value[1]='\0';
       return VAR;}
[-+*/"^"\n] return *yytext;
[ \t]  ;
.      yyerror("Invalid Char");

%%

int yywrap(void)
{
  return 1;
}



Yacc file:

%{
  void yyerror(char *);
  int yylex(void);  
  #include<stdio.h>
  char prefix[300];
  char postfix[300];
  char temp[52];
%}

%union { char value[300]; }
%token <value> VAR
%type <value> exp term fact

%%

program: exp '\n' { printf("%s\n",$1); }
         ;

exp:     term { strcpy($$,$1); }
         | exp '+' term { /*strcat ($$,$1);*/
                        strcat ($$,$3);
                        strcat ($$,"+"); }
         | exp '-' term { /*strcat ($$,$1)*/;
                          strcat ($$,$3);
                          strcat ($$,"-"); }
         ;

term:    fact { strcpy($$,$1); }
         | term '*' fact { strcat ($$,$3);
                           strcat ($$,"*"); }
         | term '/' fact { strcat ($$,$3);
                           strcat ($$,"/"); }

fact:    VAR { strcpy($$,$1); }
         | fact '^' VAR { strcat ($$,$3);
                          strcat($$,"^"); }
%%

void yyerror(char *s) {
  fprintf(stderr, "%s\n", s);
}

int main(void) {
  yyparse();
  return 0;
}



The code itself it suppose to convert a variable only infix expression to a postfix and prefix notation one. I've been trying to use 2 global strings instead of the "$$" so I can make the postfix and prefix at the same time but I can only get the correct result if I do one or the other using "$$". Does anyone know of a way to use the global strings instead of that? Also, after the first time I enter an expression it is suppose to prompt me for another until I enter a EOF character but it seems to give just give a syntax error after the program looks at one expression. Would appreciate any advice anyone has, thanks. Or if anyone knows a more yacc/lex geared forum that might be able to answer me please give me the URL... CodeguruX PS- The yacc and lex version I'm using is for regular C code not C++ but it can be used for C++ I think. [Edited by - CodeguruX on December 15, 2005 8:47:49 PM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.