这是一个学生成绩的输入输出程序,但是运行似乎陷入死循环。不断的显示:please input name。我定义了两个函数read()和write(),分别是读入学生成绩和输入学生成绩。
/*源程序*/
#define numlen 10
#define scorelen 5
#define total 3
#include<stdio.h>
struct achievement
{char *name;
char number[numlen];
int score[scorelen];
};
struct achievement stu[total];
int read(struct achievement *stu)
{int i,m,len,num;
char buf[40];
printf(“please input name:\n”);
if(scanf(“%s”,buf)==1)
{len=strlen(buf);
stu->name=(char *)malloc(len+1);
strcpy(stu->name,buf);
}
else return 0;
printf(“please input number:\n”);
if(scanf(“%s”,buf)==1)
strcpy(stu->number,buf);
else
{free(stu->name);
return 0;
}
printf(“please input score”);
for(i=0;i<5;i++)
{if(scanf(“%d”,&num)==1)
stu->score[i]=num;
else break;
}
for(m=i;m<=4;m++)
stu->score[m]=0;
return 1;
}
int write(struct achievement *stu)
{int i;
printf(“name :%s\n”,stu->name);
printf(“number :%s\n”,stu->number);
printf(“score :”);
for(i=0;i<=4;i++)
printf(“%d”,stu->score[i]);
}
main()
{int i,n;
printf(“please input the students’ achievement:\n”);
for(n=0;n<total;n++)
{read(stu+n);
printf(“please input the next’s:\n”);
}
for(i=0;i<=n;i++)
write(stu+i);
}
>> 本文固定链接: http://www.vcgood.com/archives/1749
>> 转载请注明: liucheng311 2007年07月27日 于 C语言帝国 发表
检查一下int read()的值
你的失误:
1.代码写的太乱,毫无缩进,可读性极差
2.使用了strlen()就必须有头文件<string.h>,malloc也必须有<stdlib>
3.write()并不需要返回值,void wrrite()就行
我给你改了,自己看看
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#define numlen 10
#define scorelen 5
#define total 3
struct achievement
{
char *name;
char number[numlen];
int score[scorelen];
};
struct achievement stu[total];
int read(struct achievement *stu)
{
int i, m, len, num;
char buf[40];
printf(“please input name:\n”);
if (scanf(“%s”, buf) == 1)
{
len = strlen(buf);
stu->name = (char *)malloc(len + 1);
strcpy(stu->name, buf);
}
else return 0;
printf(“please input number:\n”);
if (scanf(“%s”, buf) == 1)
strcpy(stu->number, buf);
else
{
free(stu->name);
return 0;
}
printf(“please input score”);
for (i = 0; i < 5; i++)
{
if (scanf(“%d”, &num) == 1)
stu->score[i] = num;
else
break;
}
for (m = i; m <= 4; m++)
stu->score[m] = 0;
return 1;
}
void write(struct achievement *stu)
{
int i;
printf(“name :%s\n”, stu->name);
printf(“number :%s\n”, stu->number);
printf(“score :”);
for (i = 0; i <= 4; i++)
printf(“%d”, stu->score[i]);
}
void main()
{
int i, n;
printf(“please input the students’ achievement:\n”);
for (n = 0; n < total; n++)
{
read(stu + n);
printf(“please input the next’s:\n”);
}
for (i = 0; i <= n; i++)
write(stu + i);
}
不好意思原来代码发上来都变得乱了
还有我用的 VC++6。0 可能有些地方和你的不同,所以给你指出的错误也不一定是你的错 ………….