簡體   English   中英

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

[英]How to properly use fscanf in this file

我有以下內容的文件:

Bob Human,1歲

約翰·卡特3歲

瑪麗狗2

如何正確使用fscanf在結構中包含每個字符串和整數。

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

然后我創建一個_entry_數組

entry a[3];

_a_如何使用fscanf正確獲取每個值?

編輯:

我已經試過了:

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

但是它似乎兩次通過了最后一行。

您接近了,但是您沒有正確處理逗號。

像往常一樣,讀取整行然后解析它們要容易得多。 因此,讓我們這樣做。

嘗試:

char line[1024];

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

如果所有字段都已轉換,則返回值為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