gpt4 book ai didi

在 C 中计算行数并显示结构数组

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

这就是我到目前为止所拥有的。我需要读取文件day.txt,计算文件中的行数

#include "stdio.h"
#include "stdlib.h"

#define MAX_LINE_LENGTH

struct earthquake_t{
float lat;
float lng;
float dep;
float mag;
};
FILE* fid;
int main(void)
{
double lat,lng dep,mag;
double userminlat,userminlng,usermaxlat,usermaxlng,minlat,minlng,maxlat,maxlng,i, ch,line;
struct earthquake_t *earthquake;

fid=fopen("day.txt","r");

while (!feof(fid))
{ /*Need help counting lines*/
count = fscanf(fid," %lf %lf %lf\n",&lng,&lat,&dep,&mag);
/* count tell you how many of the % fields were matched,
and you need to make sure all three were found to avoid blank lines*/

if (count ==3)
{
line ++;
}
}

fseek(fid,1,SEEK_SET);
print("%d\n",sizeof(struct earthquake_t));
earthquake = (struct earthquake_t *)malloc(sizeof(struct earthquake_t)*line);

for (i=0;i<line;i++)
{
fscanf("fid,%lf %lf %lf\n",&lng,&lati,&elevi)
earthquake[i].lat=lat;
earthquake[i].lng=lng;
earthquake[i].dep=dep;
earthquake[i].mag=mag;


/*Setting the min and max values for latitude and longatidue*/
if(earthquake[i].lng >maxlng)
{
maxlng = earthquake[i].lng;
}
if(earthquake[i].lng >minlng)
{
minlng = earthquake[i].lng;
}
if(earthquake[i].lat >maxlat)
{
maxlat = earthquake[i].lat;
}
if(earthquake[i].lat >minlat)
{
minlat = earthquake[i].lat;
}

}

最佳答案

我将使用 fgets() 从文本文件中获取整行并将其放入字符串中,然后使用 sscanf() 提取您的值。

/* count tell you how many of the % fields were matched,
and you need to make sure all three were found to avoid blank lines*/

scanf man page部分说明:

返回值

这些函数返回成功匹配和分配的输入项的数量,该数量可能少于提供的数量,如果早期匹配失败,甚至为零。

如果在第一次成功转换或匹配失败发生之前到达输入末尾,则返回值 EOF。如果发生读取错误,也会返回 EOF,在这种情况下,会设置流的错误指示符(请参阅ferror(3)),并设置 errno 来指示错误。

您可以检查 line[0] == '\n' 以避免空行。

希望有帮助。

关于在 C 中计算行数并显示结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551609/

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