所以,我正在使用词法分析器,在所有的 flex 恶作剧之后我得到了这个文本:
ISEP 1252 "ADDRESS"
"Name1" 1253 "INFORMATICA"
"Name2" 1254 "Boilerplate1"
"Name3" 1255 "Boilerplate2"
"Name4" 1256 "Boilerplate3"
"Name5" 1257 "Boilerplate4"
"Name6" 1258 "Boilerplate5"
并将其存储在
yytext
中,然后使用 strtok
将每一行和该行的内容分开:
// get first line
char* line = strtok(yytext, "\n");
// get school name
char* schoolName = strtok(line, " \t");
// get school num students
int schoolNumStudents = atoi(strtok(NULL, " \t"));
// get school address inside the quotes
char* schoolAddress = strtok(NULL, "\"");
strcpy(schools[schoolCount].name, schoolName);
schools[schoolCount].numStudents = schoolNumStudents;
strcpy(schools[schoolCount].address, schoolAddress);
//print school[schoolCount]
printf("Escola: %s\n", schools[schoolCount].name);
printf("Num alunos: %d\n", schools[schoolCount].numStudents);
printf("Morada: %s\n", schools[schoolCount].address);
// get teachers
line = strtok(NULL, "\n");
while (line != NULL) {
char* teacherName = strtok(line, "\"");
int teacherExt = atoi(strtok(NULL, " \t"));
char* teacherDepartment = strtok(NULL, "\"");
schools[schoolCount].numTeachers++;
if(schools[schoolCount].teachers == NULL) {
schools[schoolCount].teachers = (struct Teacher*) malloc(sizeof(struct Teacher));
}
else {
schools[schoolCount].teachers = (struct Teacher*) realloc(schools[schoolCount].teachers, sizeof(struct Teacher) * (schools[schoolCount].numTeachers));
}
printf("Nome: %s\n", teacherName);
printf("Ext: %d\n", teacherExt);
printf("Departamento: %s\n", teacherDepartment);
line = strtok(NULL, "\n");
}
schoolCount++;
这里要看到的是,作为我提供的字符串
yytext
,第二个 strtok(NULL, "\n")
返回 NULL
而不是第二行。有什么我想念的吗?
PS:除了我提供的代码之外,没有任何与C相关的代码,代码块嵌套在lex规则中。
我尝试将 yytext 的内容复制到另一个变量,因为 strtok 改变了变量并且 yytext 保留给 lex,这没有完成任何事情,我尝试清除 strtok 缓冲区并在第二行开始重试 strtok,也没有'没用。
问题是在为子字符串行调用
strtok
之后
char* line = strtok(yytext, "\n");
// get school name
char* schoolName = strtok(line, " \t");
//..
函数
strtok
在数组line
中保留一个指针。所以下一次调用 strtik
line = strtok(NULL, "\n");
指的是
line
而不是yytext
。
避免该问题的一种方法是计算 存储在
line
中的字符串,例如
char *pos = yytext;
char* line = strtok( pos, "\n");
size_t n = strlen( line );
//...
并将该值用作数组
yytext
内的偏移量,用于数组strtok
的下一次调用
yytext
pos += n;
line = strtok( pos, "\n");
//...