此问题已在此处有答案:
Nested strtok function problem in C [duplicate](2个答案)
6天前关闭。
所以,我使用了lexer,在所有的flex恶作剧之后,我得到了这个文本:
ISEP 1252 "ADDRESS"
"Name1" 1253 "INFORMATICA"
"Name2" 1254 "Boilerplate1"
"Name3" 1255 "Boilerplate2"
"Name4" 1256 "Boilerplate3"
"Name5" 1257 "Boilerplate4"
"Name6" 1258 "Boilerplate5"
并将其存储在yytext
中,然后im继续使用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,也没有工作。
1条答案
按热度按时间lhcgjxsq1#
问题是在为子字符串行调用
strtok
之后函数
strtok
将指针保持在数组line
内。所以下一次调用strtok
指
line
而不是yytext
。避免这个问题的一种方法是计算存储在
line
中的字符串的长度,例如并将该值用作数组
yytext
内的偏移量,以便下次调用数组yytext
的strtok