gpt4 book ai didi

在 C 中创建词法分析器

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:20 25 4
gpt4 key购买 nike

我正在尝试用 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;
}

我没有得到正确的输出,只看到一个空白屏幕而不是输出。

谁能告诉我哪里出错了??提前非常感谢..

最佳答案

自从这个问题之后你问了几个问题,所以我想你已经继续了。关于您的问题和您开始的解决方案可以帮助其他人开始解决类似问题,有几件事需要注意。 You'll also find that people can often be slow at answering things that are obvious homework .我们经常等到作业截止日期过去了。 :-)

首先,我注意到您使用了一些特定于 Borland C 编译器的非标准功能,并且不会使解决方案具有可移植性或通用性。你可以在没有他们的情况下很好地解决问题,这通常是一个不错的选择。例如,您使用了 #include <conio.h> 只是为了clear the screen with a clrscr(); 这可能是不必要的,并且与词法分析器问题无关。

我测试了该程序,并且按照编写的那样运行!它转录文件的所有行 Sum.cstdout .如果您只看到一个空白屏幕,那是因为找不到该文件。要么你没有把它写到你的 C:\目录或具有不同的名称。正如@WhozCraig 已经提到的 you need to check that the file was found and opened properly .

我看到您正在使用 C 函数 strtok将输入分成标记。有一些nice examples of using this in the documentation you could include in your code ,它比您的简单案例做得更多。正如@Grijesh Chauhan 所提到的,有比 \n 更多的分隔符需要考虑。 , 或行尾。例如,空格和制表符。

然而,在程序中,事物并不总是由空格和行分隔。举个例子:

result=(number*scale)+total;

如果我们只使用空格作为分隔符,那么它不会识别所使用的单词,只会提取整个表达式,这显然不是分词。我们可以将这些东西添加到分隔符列表中:

char seprators [] = "\n=(*)+;";

然后您的代码也会挑选出这些词。该策略仍然存在缺陷,因为在编程语言中,那些符号也是需要识别的标记。编程语言标记化的问题是标记之间没有明确的分隔符。

这背后有很多理论,但基本上我们必须写下构成我们想要识别的标记基础的模式,而不是查看它们之间的差距,因为正如已经表明的那样,没有'没有!这些模式通常写为 regular expressions .计算机科学理论告诉我们,我们可以使用finite state automata来匹配这些正则表达式。 Writing a lexer involves a particular style of coding ,具有这种风格:

while ( NOT <<EOF>> ) {
switch ( next_symbol() ) {

case state_symbol[1]:
....
break;

case state_symbol[2]:
....
break;

default:
error(diagnostic);
}
}

所以,现在,也许学术作业的值(value)变得更加清晰。

关于在 C 中创建词法分析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18396165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com