Parsing CSV file by splitting with strsep

做~自己de王妃 提交于 2019-12-24 09:49:10

问题


I'm getting some unwanted output when attempting to parse a comma seperated value file with strsep(). It seems be be working for half of the file, with a number with only one value (ie. 0-9), but as soon as multiple values are added like for instance 512,

It will print 512 12 2 512 12 2 and so on. I'm not exactly sure if this is due to the particular style that I'm looping? Not really sure.

int main() {

        char line[1024];

        FILE *fp;

        int data[10][10];

        int i = 0;
        int j = 0;

        fp = fopen("file.csv", "r");

        while(fgets(line, 1024, fp)) {

                char* tmp = strdup(line);
                char* token;
                char* idx;

                while((token = strsep(&tmp, ","))) {

                        for (idx=token; *idx; idx++) {
                                data[i][j] = atoi(idx);
                                j++;
                        }
                }
                i++;
                j=0;

                free(tmp);

        }


         for(i = 0; i < 10; i++) {

                for(j = 0; j < 10; j++) {
                printf("%d ", data[i][j]);
                }
                printf("\n");
        }

        fclose(fp);
}

回答1:


It is because you are creating elements by using every characters in the token returned by strsep() as start via the loop

for (idx=token; *idx; idx++) {
        data[i][j] = atoi(idx);
        j++;
}

Stop doing that and create just one element from one token to correct:

while((token = strsep(&tmp, ","))) {

        data[i][j] = atoi(token);
        j++;
}

Also free(tmp); will do nothing because tmp will be set to NULL by strsep(). To free the buffer allocated via strdup(), keep the pointer in another variable and use it for freeing.



来源:https://stackoverflow.com/questions/39364170/parsing-csv-file-by-splitting-with-strsep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!