简体   繁体   中英

I am trying to read from a .csv file with fscanf

I am trying to read from a csv file but the output is not what I expected Output is this:

|1| |Dummy,Person| || 
|2| |Dummy,Person| || 
|3| |Dummy,Person| || 
|4| |Dummy,Person| ||     

I want it to be:

|1| |Dummy| |Person| 
|2| |Dummy| |Person| 
|3| |Dummy| |Person| 
|4| |Dummy| |Person| 

What should I do? Here is the code:

struct Person {
    int id;
    char firstname[50];
    char lastname[50];
} Person;

void loadPersonInfo(FILE *fp) {
    int knt;
    int id;

    for (knt = 1; knt < 5; knt++) {
        struct Person new_person;
        char firstname[50];
        char lastname[50];

        fscanf(fp, "%d , %s ,%s ", &id, firstname, lastname);

        strcpy(new_person.firstname, firstname);
        strcpy(new_person.lastname, lastname);
        new_person.id = id;
        People[knt] = new_person;
        printf("|%d| |%s| |%s| \n", People[knt].id, People[knt].firstname,
               People[knt].lastname);
    }
}

void readFile() {
    printf("Reading Data From People.csv File.\r\n ");
    FILE *fp;
    fp = fopen("People.csv", "r");
    if (fp == NULL) {
        printf("File could not be opened \r\n");
    } else {
        loadPersonInfo(fp);
    }
    fclose(fp);
    printf("Done!\r\n");
}

Because %s is not stopping on , . It is stopping on first non-whitespace character. So first %s in your scanf reads the line up until the newline character, including the , and second field.

A %[^,] would stop on first , . Make sure to check the return value from fscanf . Don't use %s or %[ without specifying maximum width, so that you protect against overflow errors.

int ret = fscanf(fp, "%d,%49[^,],%49[^\n]", &id, firstname, lastname);
if (ret != 3) { 
      // AAaaa! error
      abort();
}

cppreference scanf .

for (knt = 1; knt < 5; knt++)

Note that arrays are indexed from 0, not from 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM