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;
}