所以我的文件格式如下:
2
4 8 4 10 6
9 6 74
第一行实际上是文件后面的行数。我想逐行读取文件(注意每行中有不同数量的标记,但都具有格式:1 个标记,然后是未指定数量的标记对)并为每行做两件事:
1)知道这一行有多少个令牌。
2) 将每个标记分配给一个变量。使用类似于以下的结构:
typedef struct {
unsigned start; //start node of a graph
unsigned end; // end node of a graph
double weight; //weight of the edge going from start to end
} edge ;
typedef struct {
unsigned id; // id of the node
unsigned ne; // number of edges adjacent to node
edge *edges; // array of edge to store adjacent edges of this node
} node;
一些代码:
FILE *fin;
unsigned nn;
node *nodes;
fin = fopen ("input.txt", "r");
fscanf(fin,"%u\n", &nn);
nodes = malloc(nn*sizeof(node));
for(i=0; i < nn; i++) { //loop through all the rows
/*grab the row and split in parts, let's say they are part[0], part[1]... */
/*and there are N tokens in the row*/
nodes[i].id=part[0];
nodes[i].ne=(N-1)/2; //number of pairs excluding first element
nodes[i].edges=malloc( (N-1)/2)*sizeof(edge) );
for(j=0; j< (N-1)/2; j++){
nodes[i].edges[j].start=part[0];
nodes[i].edges[j].end=part[2*j+1];
nodes[i].edges[j].weight=part[2*j+2];
}
}
我需要弄清楚如何执行第一个 for 循环中注释的部分,以获取令牌的数量,并将它们中的每一个作为要分配的单一令牌。有任何想法吗?
编辑:为了清楚起见,每一行都有第一个整数,然后是可变数量的对。我想按如下方式存储数据:
如果文件读取
2
4 8 4 10 6 //(2 pairs)
9 6 74 //(1 pair)
然后
nn=2;
node[0].id=4;
node[0].ne=2; //(2 pairs)
node[0].(*edges) //should be a vector of dimension ne=2 containing elements of type edge
node[0].edges[0].start=4; //same as node[0].id
node[0].edges[0].end=8;
node[0].edges[0].weight=4;
node[0].edges[1].start=4; //same as node[0].id
node[0].edges[1].end=10;
node[0].edges[1].weight=6;
node[1].id=9;
node[1].ne=1; //(1 pair)
node[1].(*edges) //should be a vector of dimension ne=1 containing elements of type edge
node[1].edges[0].start=9; //same as node[1].id
node[1].edges[0].end=6;
node[1].edges[0].weight=74;