【发布时间】:2020-04-12 20:00:49
【问题描述】:
嘿,我想从 c 中的文件的列表中创建一个邻接矩阵,但我不知道该怎么做。 到目前为止,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct value {
int num;
char start_vertex[250];
char destination_vertex[250];
} value;
int main()
{
const int nLines = 43; // number of lines in my text file
FILE * fptr;
value * valuesPtr = malloc(sizeof(value) * nLines);
if (!valuesPtr) {
puts("cannot allocate memory");
return -1;
}
if((fptr = fopen("energy.txt", "r")) == NULL)
{
perror("Error opening file");
return -1;
}
for(int i = 0; i < nLines; i++ )
{
if (fscanf(fptr, "%249s %249s %d",
valuesPtr[i].start_vertex,
valuesPtr[i].destination_vertex,
&valuesPtr[i].num) != 3) {
printf("errored file line %d\n", i);
break;
}
printf("\nStart vertex: %s \nDestination vertex: %s \nWeight: %d\n\n",
valuesPtr[i].start_vertex, valuesPtr[i].destination_vertex, valuesPtr[i].num);
}
free(valuesPtr);
fclose(fptr);
return 0;
}
能量文件里面有以下内容
York Hull 60
Leeds Doncaster -47
Liverpool Nottingham 161
Manchester Sheffield 61
Reading Oxford -43
Oxford Birmingham 103
Birmingham Leicester 63
Liverpool Blackpool 79
Carlisle Newcastle 92
Nottingham Birmingham 77
Leeds York 39
Glasgow Edinburgh 74
Moffat Carlisle 65
Doncaster Hull 76
Northampton Birmingham 90
Leicester Lincoln 82
Sheffield Birmingham 122
Lincoln Doncaster 63
Sheffield Doncaster 29
Bristol Reading 130
Hull Nottingham 145
Blackpool Leeds 116
Birmingham Bristol 139
Manchester Leeds 64
Carlisle Blackpool 140
Leicester Northampton -61
Newcastle York 135
Glasgow Moffat -28
Leicester Sheffield 100
Carlisle Liverpool -30
Birmingham Manchester 129
Oxford Bristol 116
Leeds Hull 89
Edinburgh Carlisle 154
Nottingham Sheffield 61
Liverpool Manchester 56
Carlisle Glasgow 50
Sheffield Lincoln 74
York Doncaster 55
Newcastle Edinburgh 177
Leeds Sheffield 53
Northampton Oxford 68
Manchester Carlisle 20
总共有 21 个城市(节点),文件中的每一行显示从一个城市移动到另一个城市(边缘)需要多少能量。我想将数据保存到一个矩阵中,以便以后进行进一步计算。
【问题讨论】:
标签: c adjacency-matrix