我需要编写一个程序,从文件中读取学生的详细信息并将它们存储到一个结构数组中。之后,我需要通过提示用户来过滤数据。我的输入文件如下:
Kristina
Science 30
Desmond
Geography 78
Fred
Science 87
Kristina
History 45
Desmond
Mathematics 34
我声明我的结构将数据存储为
typedef struct {
char name[102];
char subject[40];
int marks;
}Student;
我需要询问用户是想按名称还是按主题查看数据。如果他选择姓名,那么他将需要选择要显示的数据。例如,如果他选择名字Kristina
,程序应该输出
Kristina
Science 30
History 45
我设法从文件中读取数据并将数据存储到结构数组中,但我一直在编写函数来输出过滤后的数据。我的函数代码是
Student* filter_name(char choice[], Student* res, int index)
{
int i;
choice[strcspn(choice,"\n")]=0;
for(i=0;i<index;i++)
{
if (strcmp(choice,res[i].name)==0)
{
return res;
}
}
}
在我运行我的代码之后,它仍然是之前从文件中读取的相同结构数组。我需要过滤后的数组以便稍后在我的程序中对其进行排序。
我需要匹配元素的副本,因为我还需要现有数组用于其他目的。
谁能告诉我如何返回过滤后的数组?
最佳答案
您有多个问题需要解决。
首先,您的过滤函数将转到 return multiple values - 过滤后的数组本身及其大小(长度)。正如链接的问题所暗示的,您需要使用 struct
或通过指针返回值。例如后者:
Student* filter_by_name(char* name,Student* students,int students_size, int* filtered_size)
{
...
}
其次,代码本身。由于您想为现有学生复制数据,因此您应该分配结果数组:
Student* filtered = malloc(students_size * sizeof(Student));
然后对学生做一个循环:
for (int i = 0; i < students_size; ++i)
{
...
}
在循环内,检查名称是否匹配。如果是,不返回而是从数组students
复制一个元素到数组filtered
:
filtered[(*filtered_size)++] = students[i];
请注意我如何使用 filtered_size
的后增量将新元素复制到新数组的尾部。这会跟踪新数组的大小。
关于c - 如何通过特定参数过滤结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50317615/