C语言 Strtok无法正常阅读具有多行的字符串[重复]

x0fgdtte  于 2023-04-29  发布在  其他
关注(0)|答案(1)|浏览(119)

此问题已在此处有答案

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,也没有工作。

lhcgjxsq

lhcgjxsq1#

问题是在为子字符串行调用strtok之后

char* line = strtok(yytext, "\n");
// get school name
char* schoolName = strtok(line, " \t");
//..

函数strtok将指针保持在数组line内。所以下一次调用strtok

line = strtok(NULL, "\n");

line而不是yytext
避免这个问题的一种方法是计算存储在line中的字符串的长度,例如

char *pos = yytext;

char* line = strtok( pos, "\n");
size_t n = strlen( line );
//...

并将该值用作数组yytext内的偏移量,以便下次调用数组yytextstrtok

pos += n;
line = strtok( pos, "\n");
//...

相关问题