私は、コンパイラと、.txtファイルから複数行の方程式(各行に1つの方程式)を入力することを学ぶことに慣れています。そして私はセグメンテーションフォールトの問題に直面しています。算術yaccプログラムの入力ファイルを複数行読み込むには?
YACCコード:
%{
#include <stdio.h>
#include <string.h>
#define YYSTYPE int /* the attribute type for Yacc's stack */
extern int yylval; /* defined by lex, holds attrib of cur token */
extern char yytext[]; /* defined by lex and holds most recent token */
extern FILE * yyin; /* defined by lex; lex reads from this file */
%}
%token NUM
%%
Begin : Line
| Begin Line
;
Line : Calc {printf("%s",$$); }
;
Calc : Expr {printf("Result = %d\n",$1);}
Expr : Fact '+' Expr { $$ = $1 + $3; }
| Fact '-' Expr { $$ = $1 - $3; }
| Fact '*' Expr { $$ = $1 * $3; }
| Fact '/' Expr { $$ = $1/$3; }
| Fact { $$ = $1; }
| '-' Expr { $$ = -$2; }
;
Fact : '(' Expr ')' { $$ = $2; }
| Id { $$ = $1; }
;
Id : NUM { $$ = yylval; }
;
%%
void yyerror(char *mesg); /* this one is required by YACC */
main(int argc, char* *argv){
char ch;
if(argc != 2) {printf("useage: calc filename \n"); exit(1);}
if(!(yyin = fopen(argv[1],"r"))){
printf("cannot open file\n");exit(1);
}
yyparse();
}
void yyerror(char *mesg){
printf("Bad Expression : %s\n", mesg);
exit(1); /* stop after the first error */
}
LEXコード:
%{
#include <stdio.h>
#include "y.tab.h"
int yylval; /*declared extern by yacc code. used to pass info to yacc*/
%}
letter [A-Za-z]
digit [0-9]
num ({digit})*
op "+"|"*"|"("|")"|"/"|"-"
ws [ \t\n]
other .
%%
{ws} { /* note, no return */ }
{num} { yylval = atoi(yytext); return NUM;}
{op} { return yytext[0];}
{other} { printf("bad%cbad%d\n",*yytext,*yytext); return '?'; }
%%
/* c functions called in the matching section could go here */
私は結果と一緒に式を印刷しようとしています。 ありがとうございました。あなたのパーサで
rici私はそれをyaccコードをコンパイルすると成功するが、20のシフト/メッセージ。私は出力を得ることができますが、式は.txtではありません。例:2 + 3 *( - 7)は.txtですが、ファイルリーダーコードを書くと、yyerrorメッセージがスローされます。 –
@nikul:回答した後で質問を変更しないでください。 SOは質問と回答のリポジトリであることを意図しています。質問を変更すると回答が無効になり、その情報は他の人に価値がありません。答えがあなたに役立つなら、あなたはそれに投票したり、それを受け入れることができます。あなたがそれをダウンボートしたり、無視したりすることはできますが、どちらの場合でも別の質問がある場合は、別の質問としてそれを聞いてください。 – rici
すみません、私はこのサイトを初めて知りませんでした。 –