图的邻接矩阵表示法

本程序实现了图的邻接矩阵表示法,处理了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; i n;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; i n;i++) 28 for(j = 0; j n;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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值