简体   繁体   中英

How to properly use fscanf in this file

I have this file with the following contents:

Bob Human, 1

John Cat, 3

Mary Dog, 2

How can I properly use fscanf to have each string and integer in a struct.

typedef struct {
    char name[20];
    char surname[20];
    int code;
} entry;

Then I create an array of _entry_

entry a[3];

How will _a_ get each value properly using fscanf ?

EDIT :

I have tried this:

while(TRUE) {
    nscan=fscanf(infile, "%s %s d%c", temp.name, temp.surname, &temp.code, &termch);
    if(nscan==EOF) break;
    if(nscan!=4 || termch!='\n') {
        printf("Error\n");
    }
    RecBSTInsert(&a, temp);
}

But it seems to pass the last line twice.

You're close, but you're not handling the comma properly.

As usual, it's much easier to read whole lines, then parse them. So let's do that.

Try:

char line[1024];

if(fgets(line, sizeof line, infile) != NULL)
{
  nscan = sscanf(line, "%s %[^,], %d", temp.name, temp.surname, &temp.code);
}

The return value will be 3 if all the fields converted, else you have an error.

#include <stdio.h>

typedef struct{
    char name[20];
    char surname[20];
    int code;
} entry;

int main(){
    entry temp, a[3];
    FILE *infile = fopen("data.txt", "r");
    int i=0, n;
    while(fscanf(infile, "%19s %19[^,], %d", temp.name, temp.surname, &temp.code)==3){
        a[i++] = temp;
        if(i==3)break;
    }
    fclose(infile);
    n = i;
    for(i=0;i<n;++i){
        printf("%s %s, %d\n", a[i].name, a[i].surname, a[i].code);
    }
    return 0;
}

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