1

I'm writing my first Ragel program. My goal is to write a Four function calculator. Please do not send me your code. This is intended to be a learning experiance for me.

What I want to do is to match a regular expression with a float and print out the value. The Ragel program and the C/CPP code compiles, but my return value is always zero and the print statement is never executed. Below is my code. What have I done wrong?

/*
 * This is a four function calculator.
 */

#include <string.h>
#include <stdio.h>
#include <stdlib.h>


%%{
    machine calculator; 
    write data;
}%%

float calculator(char* string)
{
    int cs;
    char* p;
    char* pe;
    char* eof;
    int act;
    char* ts;
    char* te; 

    float value;
    int length;

    length = strlen(string);
    string[length -1] = 0;


    %%{ 
        action get_value {
            value =  atof(string);
        }

        action cmd_err {
            printf("Error\n");
            fhold;
        }

        main := ([0-9])@get_value;

        # Initialize and execute.
        write init;
        write exec;
    }%%

    return value;
};

#define BUFSIZE 1024

int main()
{
    char buf[BUFSIZE];
    float val;
    val = 0.0;

    while ( fgets( buf, sizeof(buf), stdin ) != 0 ) {
        val = calculator( buf );
        printf( "%f\n", val );
    }
    return 0;
}
Jongware
  • 22,200
  • 8
  • 54
  • 100
stuart
  • 39
  • 1

2 Answers2

1

You not only need to set p to point to the beginning of your buffer, but you should also point pe and eof to the end of it. This code should cover it, right after length is assigned:

p = string;
pe = string + length - 1;
eof = pe;

Note: act, ts, and te shouldn't be needed in this case since those variables are only used for scanners.

John Sensebe
  • 1,386
  • 8
  • 11
0

You didn't set up the char *p buffer with the content you are trying to parse. That's why your tests has no output.

Ragel need to know where the data to parse is located. char *p must point to the data to analyse as stated in the first example page 6 of the online documentation

Gnusam
  • 38
  • 1
  • 6