我正在加载文件:
05 11 2014 14 53 00
AB01 52.408 -4.217
XY23 51.750 -4.300
PQ29 52.100 -6.000
NY23 52.000 -5.900
第一行被放入dateTime结构中。然后我的代码应该遍历其余的行,将它们放入一个链接的结构列表中。但是,它会在无限循环中创建相同元素的链接列表。
typedef struct observer{
char id[21];
float lat;
float longitude;
struct observer *next;
} observer;
printf("Please enter the name of the observer file: ");
scanf("%s", fileName);
FILE* f1 = fopen(fileName, "r");
if(f1 == NULL)
{
perror("Error opening file");
return;
}
fscanf(f1, "%d %d %d %d %d %d", &dateTime.date, &dateTime.month,
&dateTime.year, &dateTime.hour, &dateTime.minute, &dateTime.second);
while(fscanf(f1, "%s %f %f", temp_id, &temp_lat, &temp_long))
{
struct observer *new_obs = make_observer(temp_id, temp_lat, temp_long);
insert_observer(new_obs, &observer_start);
print_observer(&observer_start);
}
fclose(f1);
observer* make_observer(char *id, float lat, float longitude)
{
observer *node = (observer*) malloc(sizeof(observer));
strcpy(node->id, id);
node->lat = lat;
node->longitude = longitude;
node->next = NULL;
return node;
}
void insert_observer(observer *node, observer **list)
{
observer *current;
observer *previous = NULL;
//int inserted = 0;
if(*list == 0)
{
*list = node;
return;
}
current = *list;
while(current != NULL)
{
if(previous != NULL)
{
previous->next = node;
}
else
{
*list = node;
}
previous = current;
current = current->next;
}
}
答案 0 :(得分:0)
尝试将插入功能更改为:
void insert_observer(observer *node, observer **list)
{
if (*list)
{
observer *current = *list;
observer *previous;
while (current)
{
previous = current;
current = current->next;
}
previous->next = node;
}
else
*list = node;
}
这只是查找列表的结尾并将节点附加到最后一个列表项。
您还需要更改主循环while
条件以检查是否已读取预期的字段数:
while (fscanf(f1, "%s %f %f", temp_id, &temp_lat, &temp_long) == 3)