简体   繁体   English

如何在此文件中正确使用fscanf

[英]How to properly use fscanf in this file

I have this file with the following contents: 我有以下内容的文件:

Bob Human, 1 Bob Human,1岁

John Cat, 3 约翰·卡特3岁

Mary Dog, 2 玛丽狗2

How can I properly use fscanf to have each string and integer in a struct. 如何正确使用fscanf在结构中包含每个字符串和整数。

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

Then I create an array of _entry_ 然后我创建一个_entry_数组

entry a[3];

How will _a_ get each value properly using fscanf ? _a_如何使用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. 如果所有字段都已转换,则返回值为3 ,否则会出现错误。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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