问题是找到一组学生的最大平均值。如您所知,Structure 在这里起作用,在我看来,首先使用 Array of Structure 制作该结构是一个好主意(或者也许),因为我有 30 个学生。然后搜索该结构的成员并找到最终答案。
但我遇到了一个问题,我无法填充 struct Stdinfo student[stdnum]
并且我的 for
循环实际上无法正常工作,我不知道不知道为什么!
作为检查,我使用 printf()
打印其中一个成员,但我不能。
这是我的代码:
#include <stdio.h>
struct Stdinfo
{
char name[30];
int score;
};
struct Stdinfo function();
int main(int argc, char **argv)
{
//Number of students ~stdnum
int stdnum, i;
puts("Input numbers of student(s) :");
scanf("%i", &stdnum);
stdnum--;
struct Stdinfo student[stdnum];
//Filling array of structure
for (i = 0; i < stdnum; i++)
{
student[i] = function();
}
return 0;
}
struct Stdinfo function()
{
struct Stdinfo student;
puts("Input the name of the student : ");
fgets(student.name, sizeof(student.name), stdin);
puts("Input his(her) score:");
scanf("%i", &student.score);
return student;
}
现在搜索不是我的主要问题,我感谢任何帮助我解决“Structure's members filing”问题的帮助。
您错误地减小了数组的大小。这样做时,您将忽略最后一个学生。丢弃该减量。
现在想想输入是怎么来的。用户输入学生人数,然后回车!
scanf("%i",&stdnum);
将消耗数字,但不会消耗换行符(来自 Enter)。
因此,fgets()
将读取该换行符并停在那里。换句话说,它认为这就是输入的实际内容。为了缓解这个问题,只需使用这个换行符,例如使用 getchar()
,在调用 fgets()
之前。
#include <stdio.h>
#include <string.h>
struct Stdinfo{
char name[30];
int score;
};
struct Stdinfo function() ;
int main(void)
{
//Number of students ~stdnum
int stdnum , i;
puts("Input numbers of student(s) :") ;
scanf("%i" ,&stdnum);
// Do not do that, it makes your program ignore the last student
//stdnum--;
struct Stdinfo student[stdnum] ;
//Filling array of structure
for(i=0 ; i < stdnum ; i++)
{
student[i] = function() ;
}
// print your array
for(i=0 ; i < stdnum ; i++)
{
printf("%s\n", student[i].name);
printf("%d\n", student[i].score);
}
return 0;
}
struct Stdinfo function() {
struct Stdinfo student;
getchar(); // Consume newline from previous input
puts("Input the name of the student : ") ;
fgets(student.name , sizeof (student.name) , stdin);
// remove trailing newline from 'fgets()'
student.name[strcspn(student.name, "\n")] = 0;
puts("Input his(her) score:") ;
scanf("%i" ,&student.score) ;
return student ;
}
PS:你可能想要Removing trailing newline character from fgets() input (我的示例就是这样做的)。