本程序实现了图的邻接矩阵表示法,处理了scanf()输入时的缓冲,用scanf()函数进行输入时,要使输入有效,必须按下‘enter’键,即
输入'/n'字符, 缓冲区的内容才会写到变量里去(标准输入时行缓冲的),正式由于'/n'带来了问题,scanf()会把'/n'放在输入缓冲队列里,那么下次再调用输入函数的时候,这个'/n'就会被读取,这不是程序真正想读的,所以用了个while()来把多余的'/n'甚至是其他的都从输入缓冲区里读出来。
源代码如下:
1 #include
2
3 #define MaxVertexNum 100
4 typedef char VerexType;
5 typedef int EdgeType;
6 typedef struct{
7 VerexType vexs[MaxVertexNum];
8 EdgeType edges[MaxVertexNum][MaxVertexNum];
9 int n,e;
10 }MGraph;
11
12 void CreateGraph(MGraph *G){
13 int i,j,k,w;
14 puts("input the vertex number and edges number");
15 if (scanf("%d%d",&G->n,&G->e)!=2)
16 exit(1);
17 while(getchar()!= '/n')
18 continue;
19 // fflush(stdin);not work on linux
20 for(i = 0; in;i++){
21 puts("vertex value,this program the value must be letter");
22 G->vexs[i] = getchar();
23 // fflush(stdin);
24 while(getchar()!='/n')
25 continue;
26 }
27 for(i = 0; in;i++)
28 for(j = 0; jn;j++)
29 G->edges[i][j]=0;
30 for(k = 0; k < G->e; k++ ){
31 puts("input i and j and weight of (Vi<-->Vj)");
32 if (scanf("%d%d%d",&i,&j,&w)!= 3)
33 exit(2);
34 G->edges[i][j] = w;
35 G->edges[j][i] = w;
36 //fflush(stdin);
37 while(getchar()!='/n')
38 continue;
39 }
40 }
41 void PrintGraph(MGraph G){
42 printf("The graph vertex = %d,edges= %d/n",G.n,G.e);
43 int i = 0;
44 int j = 0;
45 for(i = 0; i< G.n; i++)
46 printf("the vertex of the graph is %c/n", G.vexs[i]);
47 for(i = 0; i< G.n; i++)
48 for(j = 0; j< G.n; j++)
49 printf("G.edges[%d][%d]=%d/n", i,j,G.edges[i][j]);
50 }
51 int main()
52 {
53 MGraph G;
54 CreateGraph(&G);
55 PrintGraph(G);
56 }
编译:gcc graph.c -o graph
执行:./graph < input_file 调试时,省去了从键盘输入的负担。
input_file 内容如下:
4 3
a
b
c
d
1 2 100
1 3 200
2 3 300
图的邻接矩阵表示法
最新推荐文章于 2024-08-01 10:12:30 发布

1068

被折叠的 条评论
为什么被折叠?



