我正在为我的 C 算法课程做我的最后一个项目。对于这个项目,我们必须获取一个包含以下行的输入文本文件:
P|A|0
或者
E|0|1|2
前者表示要添加到我们在程序中使用的图中的顶点,第二个标记是顶点的名称,最后一个标记是它在图结构的 vertices[] 数组中的索引。
我有一个while循环逐行遍历这个程序,它需要第一个标记来决定是制作顶点还是边,然后相应地继续。
当我完成文件遍历时,我调用我的 show_vertices 函数,它只是一个按顺序打印每个名称 (g->vertices[i].name) 的 for 循环。
问题是名称应该在输出(%s)中的位置,我不断得到我收集的最后一个“token1”。在我使用的特定输入文件的情况下,它恰好是列表中最后一条边的源节点......这很奇怪,因为之后还有另外两个值通过 strtok() 函数。文件中的行如下所示:
E|6|7|1
它创建了从索引 6 到 7 的边,权重为 1。边很好。但是当我printf
用 %s 调用 any 时,它会出现“6”。不管。
这是文件遍历。
fgets(currLn, sizeof(currLn), infile);
maxv = atoi(currLn);
if(maxv = 0)
{
//file not formatted correctly, print error message
return;
}
t_graph *g = new_graph(maxv, TRUE);
while((fgets(currLn, sizeof(currLn), infile)) != NULL)
{
token1 = strtok(currLn, "|");
key = token1[0];
if(key == 'P' || key == 'p')
{
token1 = strtok(NULL, "|");
if(!add_vertex(g, token1))
{
//file integration fail, throw error!
return;
}
//***If I print the name here, it works fine and gives me the right name!****
continue;
}
if(key == 'E' || key == 'e')
{
token1 = strtok(NULL, "|");
token2 = strtok(NULL, "|");
token3 = strtok(NULL, "|");
src = atoi(token1);
dst = atoi(token2);
w = atoi(token3);
if(!add_edge(g, src, dst, w))
{
//file integration fail, throw error
return;
}
continue;
}
else
{
//epic error message because user doesn't know what they're doing.
return;
}
}
如果我在show_vertices
这里运行,我会得到:
0. 6
1. 6
2. 6
etc...