我正在编写我的第一个 Ragel 程序。我的目标是写一个四函数计算器。请不要把你的代码发给我。这对我来说是一次学习经历。
我想要做的是将正则表达式与浮点数匹配并打印出值。Ragel 程序和 C/CPP 代码可以编译,但我的返回值始终为零,并且打印语句永远不会执行。下面是我的代码。我做错了什么?
/*
* 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;
}