gpt4 book ai didi

c - 如何在 C 中使用 strtok 返回 NULL 字符串?

转载 作者:行者123 更新时间:2023-11-30 17:30:25 25 4
gpt4 key购买 nike

我正在读取 .csv 文件(以逗号分隔),以便分析数据。许多字段为空,这意味着一行可能如下所示:

456,Delaware,14450,,,John,Smith

(我们没有 John Smith 的电话号码或电子邮件地址,因此这些字段为空)。

但是当我尝试将这些行分成标记(这样我可以将它们放入矩阵中来分析数据)时,strtok 不会返回 NULL 或空字符串,而是会跳过这些字段,最终导致不匹配列。

换句话说,我想要的结果是:

a[0]=456
a[1]=Delaware
a[2]=14450
a[3]=NULL (or "", either is fine with me)
a[4]=NULL (or "")
a[5]=John
a[6]=Smith

相反,我得到的结果是:

a[0]=456
a[1]=Delaware
a[2]=14450
a[3]=John
a[4]=Smith

这是错误的。任何关于如何获得我需要的结果的建议都将受到极大的欢迎。这是我的代码:

FILE* stream = fopen("filename.csv", "r");
i=0;
char* tmp;
char* field;
char line[1024];

while (fgets(line, 1024, stream))
{
j=0;
tmp = strdup(line);
field= strtok(tmp, ",");

while(field != NULL)
{
a[i][j] =field;

field = strtok(NULL, ",");

j++;
}

i++;
}
fclose(stream);

最佳答案

引用 ISO/IEC 9899:TC3 7.21.5.8 strtok 函数

3 The first call in the sequence searches the string pointed to by s1 for the first character that is not contained in the current separator string pointed to by s2. If no such character is found, then there are no tokens in the string pointed to by s1 and the strtok function returns a null pointer. If such a character is found, it is the start of the first token.

以及您的相关报价:

4 The strtok function then searches from there for a character that is contained in the current separator string. If no such character is found, the current token extends to the end of the string pointed to by s1, and subsequent searches for a token will return a null pointer. If such a character is found, it is overwritten by a null character, which terminates the current token. The strtok function saves a pointer to the following character, from which the next search for a token will start.

所以你不能用 strtok 捕获多个分隔符,因为它不是为此而设计的。它只会跳过它们。

关于c - 如何在 C 中使用 strtok 返回 NULL 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25141908/

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