[英]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.