clex

Convert Octal numbers to Decimal numbers in Lex


I have been trying to write a Lex program to convert octal numbers to decimal numbers. But after accepting the number as input, but not doing anything. No output. And no program termination. The program is still running without any output.

What might be the error? I have a strong feeling about the yywrap and todec functions doing mischief.

Thanks in advance. :)

Source code :

%{
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    int v = 0, o = 0, d = 0; //valid bit, octal number, decimal number
%}

%%
^[0-7]+  {v = 1; o = atoi(yytext);}
[\n] {;}
. {v = 0;}
%%

int yywrap()
{
    if (v)
    {
        d = todec(o);
        printf("Decimal is %d\n", d);
    }
    else
    {
        printf("Invalid");
    }
}

int todec(int oct)
{
    int dec = 0, pos = 0;
    while(oct)
    {
        int a = oct % 10;
        dec += a * pow(8, pos);
        pos++;
        oct /= 10;
    }
    return dec;
}

int main()
{
    printf("Enter the octal number: ");
    yylex();
    return 0;
}

Solution

  • I'll quote http://dinosaur.compilertools.net/flex/flex_10.html
    *When the scanner receives an end-of-file indication from YYINPUT, it then checks the yywrap() function

    So, if you simulate EOL behaviour using ctrl-d (after entering the number and pressing the return key), you can see that your calculations are correct.

    If you want to see the results immediately, you will have to write the output after you compute it.

    Cheers