首页 > 解决方案 > 如何将从文件读取的strtok令牌添加到数组中?

问题描述

int main(){
    FILE *file;
    char line[100];
    char name[26],code[4],donator[10],shipment[10], quantity[10];
    int count = 0;

    file = fopen("donation.txt","r");

    if(!file){
        printf("File does not exist!");
        return 1;
    }

    while (!feof(file)){
        fgets(line,100,file);
        count++;
    }
    char *list[count][5];
    memset(list,0,sizeof(list));

    fseek(file,0,SEEK_SET);
    count=0;

    int count2=0;
    char dtm[sizeof(line)];
    while (!feof(file)){
        fgets(line,100,file);
        if (count>0){
            strcpy(dtm,line);
            printf("%s",dtm);
            count2=0;
            for(char  *p = strtok(dtm,"|");p ; p=strtok(NULL,"|")){
                printf("\n %d %s",count2,p);
                list[count-1][count2]=p;
                printf("\n%s",list1[count-1][count2]);
                count2++;
            }
        }
        count++;
    }
    for(int i =0; i<count-1 ;i++){
        for(int k=0;k<count2;k++)
            printf("\n%d %d %s",i,k,list[i][k]);
    }
    fclose(file);
    return 0;
}

.

Contactless Thermommeter | CT          | Japan        | 1               | 1                      
Hand Sanitizer           | HS          | USA          | 1               | 1                      
Face Mask                | FM          | China        | 1               | 1                      
Surgical Mask            | SM          | China        | 1               | 1                      
Oxygen Mask              | OM          | Saudi Arabia | 1               | 1                                               

for 循环的预期输出片段:

0 0 Contactless Thermometer<br/>
0 1  CT<br/>
0 2  Japan<br/>
0 3  1<br/>
0 4  1<br/>
1 0 Hand Sanitizer<br/>
1 1  HS<br/>
1 2  USA<br/>
1 3  1<br/>
1 4  1<br/>

for 循环的输出片段:

0 0 Oxygen Mask<br/>
0 1  OM<br/>
0 2  Saudi Arabia<br/>
0 3  1<br/>
0 4  1<br/>
1 0 Oxygen Mask<br/>
1 1  OM<br/>
1 2  Saudi Arabia<br/>
1 3  1<br/>
1 4  1<br/>

在我的大学预科课程中学习 Python 后,我刚开始使用 C,如果有人能指导我了解我的代码出了什么问题,我将非常感激。在文件读取过程中,我使用strtok将txt文件中的行分解并存储在中list[i][k],如How to store tokens(strtok) in a pointer on an array中所示。它显示了预期的值,但在下一个 for 循环中,list[i][k]仅显示了最后一组值,如下图所示。

标签: c

解决方案


好的,代码有点乱,你只是想把你的文件映射到一个二维数组中。

有几个麻烦:

    if (count>0){

为什么 ?您希望数组中的每一行都包含在内,不要跳过第一行。

            list[count-1][count2]=p;

跳过-1。它与那里无关。

            list[count-1][count2]=p;

是的,同一行有两个问题。

您在数组中分配了一个将更改的字符串上的指针。和指针别名。strtok 返回一个指向实际字符串的指针。它不会重新分配内存。

解决方案是简单地对您的字符串进行 strdup,因此它有一个新的内存,不会在下一个循环周期中更改。

            list[count][count2] = strdup(p);

不要忘记稍后释放它。不要忘记检查您的 strdup 是否失败:)

其他说明:您有未使用的变量。换行符保留在字符串中的最后一个标记中。您可能想要删除它。


推荐阅读