C 来自文件的输入将永远持续
我有下一个C代码:C 来自文件的输入将永远持续,c,input,C,Input,我有下一个C代码: #include <stdio.h> #include <stdlib.h> #include "list.h" #include "graph.h" int main() { int action, src, dst; IntGraph g; g = newIntGraph(); while (1) { printf("1 -> Add a nodes.\n"); print
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#include "graph.h"
int main() {
int action, src, dst;
IntGraph g;
g = newIntGraph();
while (1) {
printf("1 -> Add a nodes.\n");
printf("2 -> Add an arc.\n");
printf("3 -> Dump the graph.\n");
printf("4 -> BFS.\n");
printf("What do you want to do? [1, 2, 3, 4] ");
scanf("%d", &action);
switch (action) {
case 1:
addIntGraphNode(&g);
break;
case 2:
printf("Insert source and destination: ");
scanf("%d", &src);
scanf("%d", &dst);
addIntGraphArc(&g, src, dst);
break;
case 3:
dumpIntGraph(g, "GRAPH\0");
break;
case 4:
printf("Insert the node to start: ");
scanf("%d", &src);
BFSIntGraph(g, src);
break;
default:
return 0;
}
}
}
#包括
#包括
#包括“list.h”
#包括“graph.h”
int main(){
内部动作,src,dst;
图g;
g=newIntGraph();
而(1){
printf(“1->添加节点。\n”);
printf(“2->添加弧。\n”);
printf(“3->转储图形。\n”);
printf(“4->BFS.\n”);
printf(“你想做什么?[1,2,3,4]”);
scanf(“%d”、&action);
开关(动作){
案例1:
附加图形节点(&g);
打破
案例2:
printf(“插入源和目标:”);
scanf(“%d”和&src);
scanf(“%d”和&dst);
附加图(g&g、src、dst);
打破
案例3:
dumpIntGraph(g,“图\0”);
打破
案例4:
printf(“插入要开始的节点:”);
scanf(“%d”和&src);
BFSIntGraph(g,src);
打破
违约:
返回0;
}
}
}
但是我需要它来做一些测试,所以我想有一个现成的输入来生成基本图
我将输入写入一个文件(每行一个数字)。我有一个包含十行和十个1的文件,因为我希望程序生成一个包含十个节点的图
当我打字时:
/graph-test.run
它开始无休止地读取文件,添加数百个节点。我想它停止一旦文件完成,让我做一些其他的操作
我怎样才能做到这一点?如果我手动插入值,代码运行良好,因此这是一个与输入相关的问题。问题是没有检查
EOF的scanf()
返回值。如果遇到EOF
,操作将不被修改。建议:
if (1 != scanf("%d", &action)) /* scanf() returns number of assignments made,
which should be 1 in this case. */
{
break; /* exit while loop. */
}
对于每次调用scanf
检查是否返回EOF
。如果出现EOF
中断while(1)
循环
if (EOF == scanf(....))
break; //or exit(0);
你是不是想在第四个案子之后休息一下。它会像现在一样默认。是的,对不起。我忘了。顺便说一下,我的输入文件中只有1个,所以这不是问题所在。同样感谢您指出这一点。实际上,我不希望程序中断或退出,我希望它根据输入创建基本图,然后让我在添加节点、圆弧、访问它等等之间进行选择。我希望当遇到EOF时,程序将等待用户输入。用户输入是什么意思(特别是在EOF被击中之后)?用户无法通过stdio进行交互,因为您已重定向了文件中的输入..我正在学习graph,我正在自学一些c代码。我将添加其他函数,如DFS、Kruskal等。所以,我不想每次都创建图来检查我的函数是否工作。我希望程序从文件中获取输入(仅选项1和2,多次),这样我就可以在不“手动”创建图形的情况下检查其他函数。在这种情况下,您最好阅读外部文件以填充节点,并让用户逐个选择选项。好的。这不是我所希望的答案。但是你的回答回答了我的问题。非常感谢。