gpt4 book ai didi

c - 如何在 for 循环中使用 strtok()?

转载 作者:行者123 更新时间:2023-12-04 10:57:32 26 4
gpt4 key购买 nike

对于给定的表示,

typedef struct {
int age;
char *firstName;
char *lastName;
}Record;

并给定file.txt

Age,LastName,FirstName
50,B,A
30,A,B
20,X,D
10,F,A
90,V,E
60,N,M

下面是main()中的代码,

 pFile=fopen("file.txt", "r");
...
//Complete file is copied to 'readBuffer', approach inspired from
// http://stackoverflow.com/a/11487960/3317808
....

char *record = strtok(readBuffer,"\n"); //Ignore header record
record = strtok(NULL, "\n");// Read first data record(50,'B','A')

for(;record != NULL; record = strtok(NULL,"\n")){

printf("###Print complete record\n");
puts(record);

Record *r = malloc(sizeof(Record)*1);

r->age = atoi(strtok(record,","));

char *firstName = strtok(NULL,",");
char *lastName = strtok(NULL, ",");

r->firstName = strdup(firstName);
r->lastName = strdup(lastName);
printf("Age: %d\n", r->age);
printf("First name: %s\n", r->firstName);
printf("Last name: %s\n", r->lastName);

}

strtok(readBuffer,",")将编译器与 for 循环中的 strtok(record,",") 混淆


实际输出显示标记化只发生在一条记录上。

$ ./program.exe
Print complete file
Age,LastName,FirstName
50,B,A
30,A,B
20,X,D
10,F,A
90,V,E
60,N,M



###Print complete record
50,B,A
Age: 50
First name: B
Last name: A

如何解决?

最佳答案

如果在我们的例子中可能的话,使用 strtok_r() 似乎是最简单的方法。只是通知一下,这不是标准 C,它在 POSIX 中。

来自man page ,

The strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

Different strings may be parsed concurrently using sequences of calls to strtok_r() that specify different saveptr arguments.

手册页还有您正在寻找的场景的示例。

关于c - 如何在 for 循环中使用 strtok()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41421391/

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