簡體   English   中英

從 C 中的文件讀取數據

[英]Reading data from a file in C

我有一個數據文件,我想將它讀入一個結構。

這是數據文件的內容

Japan 46.2 16 12.7
Spain 42.8 18.5 39.3
Italy 53.25 19.8 32.8
France 54.5 21.1 31.4
Turkey 52.5 15.6 19.1

這是我的代碼

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

int main(){
    

    struct covid
    {
        char location[100];
        double does_given;
        double full_vaccinated;
        double of_population_fully_vaccinated;
    };

    FILE *infile;
    infile=fopen("test.txt","r");
    
    if (infile == NULL)
    {
        fprintf(stderr, "\nError opening file\n");
        exit (1);
    }

    struct covid stats;
    
    while (fread(&stats,sizeof(struct covid),1,infile)){
        printf("name =%s, give =%f, full=%f, pop=%f\n",stats.location, stats.does_given, stats.full_vaccinated, stats.of_population_fully_vaccinated);
        
    };

    fclose(infile);
    return 0;
    
}

但是,當我運行此代碼時,我沒有得到 output。 為什么它不起作用?

您的文件包含數字的文本表示,您不能盲目地將該文本讀入結構,沒有魔法可以將文本表示轉換為雙精度數。

您需要逐行讀取文件並單獨解析每一行。

你想要這樣的東西:

  char line[1000];

  while (fgets(line, sizeof(line), infile)) {
    sscanf(line, "%s %lf %lf %lf", stats.location, &stats.does_given,
                  &stats.full_vaccinated, &stats.of_population_fully_vaccinated);

    printf("name =%s, give =%f, full=%f, pop=%f\n", stats.location, stats.does_given,
            stats.full_vaccinated, stats.of_population_fully_vaccinated);
  };

免責聲明:沒有任何錯誤檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM