how to get specific rows from csv file?

▼魔方 西西 提交于 2020-02-08 11:15:19

问题


I've written a code, wherein i'm trying to get all the rows which start from "A". I have A, A12 etc in my csv file and i want to read all those rows. But i got the following error. Not sure where i went wrong. Kindly help.

CSV file

M,2,lion
A,1,tiger
B,2,cat
A1,7,dog
C,3,man
A2,9,mouse
A23,9,pouch

myfile.c

#include <stdio.h>
#include <stdlib.h>

#define NUMLETTERS 100

typedef struct {
    char letter[100];
    int number;
    char ani[100];
} record_t;

int main(void) {
    FILE *fp;
    record_t records[NUMLETTERS];
    size_t count = 0;

    fp = fopen("letters.csv", "r");
    if (fp == NULL) {
        fprintf(stderr, "Error reading file\n");
        return 1;
    }

    while (fscanf(fp, " %s,%d,%s", records[count].letter, &records[count].number, records[count].ani) == 3) {
        count++;
    }

    for (size_t i = 0; i < count; i++) {
        if(records[i].letter== "A"){
        printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].number);
    }
    }

    fclose(fp);

    return 0;
} 

Error

myfile.c:29:16: warning: format ‘%s’ expects argument of type ‘char *’, but argument 4 has type ‘int’ [-Wformat=]
         printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].number);

回答1:


Since you search fields that start with A, you only need to compare the first letter of letter, so your line 28 becomes:

if(records[i].letter[0] == 'A'){

And your compiler told you that you try to display an integer as a string, it's because you have a typo in line 29: number instead of ani, the line should be:

printf("%s,%d,%s\n", records[i].letter, records[i].number,records[i].ani);

Sorry i got my output but some extra column added in my output as "0" A,1,tiger,0, A1,7,dog,0, A2,9,mouse,0, A23,9,pouch,0, – Abhik 2 hours ago

It comes from your scanf call: in scanf, %s will read until in find a space (space or tab or line feed). You have to tell to scanf to stop too read letter after the first comma found. To do this, replace %s with %99[^,]. More explanations here: Scanf guide.

So your reading loop should looks like:

while (fscanf(fp, " %99[^,],%d,%s", records[count].letter, &records[count].number, records[count].ani) == 3) {
    count++;
}


来源:https://stackoverflow.com/questions/60006396/how-to-get-specific-rows-from-csv-file

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