Question

I'm trying to get it to read values from a file (such as 1+2) and output the answer in the console. The operators work fine and produce the correct result, but the initial values in the output are completely wrong. For example, when I tried 5+3 it displayed as 6432824 + 6432824 = 12865648, and when running it again exactly the same, displays it as 4597832 + 4597832 = 9195664. So even though 5 and 3 are different (obviously) they are displayed as the same number and seemingly randomly each time it is run. How can I fix this?

Here's the code:

Flex file:

%{
    #include <stdio.h>
    #include <stdlib.h>
    #include "y.tab.h"
    extern  FILE* yyin;
            FILE* FileOutput;
    #define YYSTYPE int
%}

%%

[0-9]+  { yylval = (int)yytext; return INTEGER; }
"+" return ADD;
"-" return SUBTRACT;
"*" return MULTIPLY;
"/" return DIVIDE;
[ \t]  ;
.       yyerror();

%%

int main(int argc, char *argv[])
{
    yyin = fopen(argv[1], "r");
    FileOutput = fopen("output.c", "w");
    yyparse();
    fclose(FileOutput);
    return 0;
}

int yywrap(void)
{
 return 1;
}

int yyerror(void)
{
 printf("Error\n");
}

Bison file:

%{
 #include <stdio.h>
 #include <stdlib.h>
 extern FILE* FileOutput;
 #define YYSTYPE int

 void createcode(int result, int a, unsigned char op, int b);

%}

%token INTEGER
%token ADD SUBTRACT MULTIPLY DIVIDE

%left ADD SUBTRACT
%left MULTIPLY DIVIDE


%%
program: 
        | program statement
        ;

statement:
        expression '\n'     { printf("%d\n", $1); }
        | error '\n'            { yyerrok; }
        ;

expression: 
        INTEGER         { $$ = $1; }
        | expression ADD expression     { $$ = $1 + $3, createcode($$, $1, '+', $3);}
        | expression SUBTRACT expression        { $$ = $1 - $3; createcode($$, $1, '-', $3);}
        | expression MULTIPLY expression        { $$ = $1 * $3; createcode($$, $1, '*', $3);}
        | expression DIVIDE expression      { $$ = $1 / $3; createcode($$, $1, '/', $3);}
        | '(' expression ')'            { $$ = $2; }
        ;

%%

void createcode(int result, int a, unsigned char op, int b)
{
    printf("%d %c %d = %d", a, op, b, result);
    fprintf(FileOutput, "%d %c %d = %d", a, op, b, result);
}
Was it helpful?

Solution

You're returning a string(char *) instead of an integer. Easiest solution is to use strtol in yylex:

i.e., instead of:

[0-9]+  { yylval = (int)yytext; return INTEGER; }

try

[0-9]+  { yylval = (int)strtol(yytext, NULL, 10); return INTEGER; }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top