Flex Specification yytext
I'm trying to build a flex specification for the k
notation, for instance: 3k5 = 3500
. I have the following:
[0-9]+{LETTER} { yyless(yyleng-1); yy_push_state(X_REAL); aux = atof(yytext); }
<X_REAL>"k"[0-9]+ { yytext[0] = "." ; printf("%f", ((atof(yytext) * 10^(3)) + aux * 10^(3))); }
However I get an error when trying to put "."
in the first char of yytext:
In member function 'virtual int AtScanner::yylex()': error: invalid conversion from 'const char*' to 'char' error: invalid operands of types 'double' and 'int' to binary 'operator^'
How can I manipulate the yytext?
You cannot modify yytext
, it's const
.
You should go another way: perhaps just allocate a new string using strdup
?
Other problem: yytext[0]
is a char
, so should be the rhs. So we need '.'
instead of "."
.
Yet another problem: 10^3
is not producing 1000, in C it's bitwise exclusive OR operator (thanks to @Chris for pointing this out). So just put plain 1000 instead.
So, the final code should look like:
<X_REAL>"k"[0-9]+ { char* number = strdup(yytext);
number[0] = '.';
printf("%f", ((atof(number) * 1000) + aux * 1000));
free(number); }
Note that I didn't check the correctness of calculations.
Modifying yytext (or a copy) seems like a bad way of going about this. Why not just extract the numbers directly?
[0-9]+k[0-9]+ { char *p;
long first = strtol(yytext, &p, 10);
long second = strtol(p+1, 0, 10);
double value = first*1000.0 + second*pow(10.0, p-yytext-yyleng+4.0);
printf("%f", value); }
链接地址: http://www.djcxy.com/p/57864.html
上一篇: 扫描EOF字符
下一篇: Flex规范yytext