gpt4 book ai didi

c - 用结构体写入结构体

转载 作者:行者123 更新时间:2023-11-30 15:26:15 25 4
gpt4 key购买 nike

我正在使用 fscanf 读取 txt 文件。

for (int i = 0; i < totalLines; ++i)
{
fscanf(fp,"%s %s %f %f[^\n]", &cp[i].name, &cp[i].animal, &cp[i].coordinates.lat, &cp[i].coordinates.lng);
printf("Name: %s\nAnimal: %s\nLat: %.6f\nLong: %.6f\n\n", cp[i].name, cp[i].animal, cp[i].coordinates.lat, cp[i].coordinates.lng);
}

问题是它不会设置/打印最里面的结构成员或变量,这些成员或变量是 2 个 double lng 和 lat 未分配。完成这项工作的最佳方法是什么?我走在正确的轨道上吗?我尝试用(双)来转换它,但由于错误。有什么想法吗?

更新

我已经将代码更新为应有的样子,但我仍然得到 0 值。有什么想法吗?

最佳答案

考虑您的结构如下:

/* Structure Holding Coordinates */
typedef struct location
{
double lat;
double longt;
}location_t;


typedef struct geo
{
char name[64];
char animal[64];
location_t loc;
} geo_t;
<小时/>

您的阅读应按如下方式完成:

geo_t arr[NO_ENTRIES];     /* NO_ENTRIES is total lines in file */                                                     
for(i = 0; i< NO_ENTRIES; i++)
fscanf(fp, " %s %s %lf %lf", arr[i].name, arr[i].animal, &arr[i].loc.lat, &arr[i].loc.longt);

printf("After Reading\n\n\n");
for(i = 0; i< NO_ENTRIES; i++)
printf(" %s %s %f %f\n", arr[i].name, arr[i].animal, arr[i].loc.lat, arr[i].loc.longt);

在这里查看:http://ideone.com/99dmvL

关于c - 用结构体写入结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27439405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com