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.
Per @rici's comment, modifying yytext
should be ok, so the code can be simplified as follows:
<X_REAL>"k"[0-9]+ { yytext[0] = '.';
printf("%f", ((atof(yytext) * 1000) + aux * 1000)); }