【发布时间】:2013-08-23 06:25:34
【问题描述】:
我正在尝试用 C 创建一个词法分析器。 程序读取另一个程序作为输入转换成token,源码在这里-
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
FILE *fp;
char read[50];
char seprators [] = "\n";
char *p;
fp=fopen("C:\\Sum.c", "r");
clrscr();
while ( fgets(read, sizeof(read)-1, fp) !=NULL ) {
//Get the first token
p=strtok(read, seprators);
//Get and print other tokens
while (p!=NULL) {
printf("%s\n", p);
p=strtok(NULL, seprators);
}
}
return 0;
}
而Sum.c的内容是-
#include <stdio.h>
int main() {
int x;
int y;
int sum;
printf("Enter two numbers\n");
scanf("%d%d", &x, &y);
sum=x+y;
printf("The sum of these numbers is %d", sum);
return 0;
}
我没有得到正确的输出,只看到一个空白屏幕代替输出。
谁能告诉我我哪里出错了? 提前非常感谢你..
【问题讨论】:
-
确保确保您的文件已成功打开。你永远不会检查它,运行时的当前工作目录通常不是你想的那样,特别是如果你是从 IDE 或其他类似工具运行的。验证
fopen()成功,如果没有,perror("Failed to open file.");并退出。至少你会知道这是问题所在。 -
如果要打印令牌,选择
seprators值为"\n";是错误的。 -
如果你真的想创建一个词法分析器,我强烈推荐你使用 Flex (en.wikipedia.org/wiki/Flex_lexical_analyser)
-
@Michael:这可能是了解词法分析器如何工作的家庭作业。在这种情况下,Flex 是最糟糕的学习方式!
-
@dave- 你说得对……这是学术作业的一部分……
标签: c parsing lexical-analysis