getchar()在程序中起什么作用
getchar()在程序中起什么作用#include <stdio.h>
#define MAXSIZE 10000
#define v 30
typedef struct node
{
char vert[v];
int edge[v][v];
int n,e;
}matrix;
void creatmatrix(matrix *gra)
{
int p,q,x,w;
printf("The n and e are:\n");
scanf("%d%d",&gra->n,&gra->e);
printf("The vertexs are:\n");
for(p=0;p<gra->n;p++)
scanf("%c",&gra->vert[p]);
for(p=0;p<gra->n;p++)
for(q=0;q<gra->n;q++)
if(p==q)
gra->edge[p][q]=0;
else
gra->edge[p][q]=MAXSIZE;
printf("The edges are:\n");
for(x=0;x<gra->e;x++)
{
scanf("%d%d%d",&p,&q,&w);
gra->edge[p][q]=w;
}
}
void print(matrix gra)
{
int p,q;
printf("\nThe vertexs are:\n");
for(p=0;p<gra.n;p++)
printf("%c",gra.vert[p]);
printf("\n");
printf("\nThe matrix is:\n");
for(p=0;p<gra.n;p++)
{
for(q=0;q<gra.n;q++)
printf("%8d",gra.edge[p][q]);
printf("\n");
}
}
int main()
{
matrix gra;
creatmatrix(&gra);
print(gra);
return 0;
}
运行结果:
The n and e are:
3 3
The vertexs are:
ABC
The edges are:
The vertexs are:
AB
The matrix is:
0 10000 10000
10000 0 10000
10000 10000 0
以上运行结果是错误的。
正确的是:
#include <stdio.h>
#define MAXSIZE 10000
#define v 30
typedef struct node
{
char vert[v];
int edge[v][v];
int n,e;
}matrix;
void creatmatrix(matrix *gra)
{
int p,q,x,w;
printf("The n and e are:\n");
scanf("%d%d",&gra->n,&gra->e);
getchar();
printf("The vertexs are:\n");
for(p=0;p<gra->n;p++)
scanf("%c",&gra->vert[p]);
for(p=0;p<gra->n;p++)
for(q=0;q<gra->n;q++)
if(p==q)
gra->edge[p][q]=0;
else
gra->edge[p][q]=MAXSIZE;
printf("The edges are:\n");
for(x=0;x<gra->e;x++)
{
scanf("%d%d%d",&p,&q,&w);
gra->edge[p][q]=w;
}
}
void print(matrix gra)
{
int p,q;
printf("\nThe vertexs are:\n");
for(p=0;p<gra.n;p++)
printf("%c",gra.vert[p]);
printf("\n");
printf("\nThe matrix is:\n");
for(p=0;p<gra.n;p++)
{
for(q=0;q<gra.n;q++)
printf("%8d",gra.edge[p][q]);
printf("\n");
}
}
int main()
{
matrix gra;
creatmatrix(&gra);
print(gra);
return 0;
}
运行结果是:
The n and e are:
3 3
The vertexs are:
ABC
The edges are:
0 2 60
2 0 74
1 2 65
The vertexs are:
ABC
The matrix is:
0 10000 60
10000 0 65
74 10000 0
运行正确的程序比运行错误的程序就多了一条"getchar();"语句;
请各位大侠帮我分析一下,十分感谢!