如何在C中搜索结构中的成员并打印所有成员?
问题描述:
我们被要求用C编写一定的方案,使用户能够如何在C中搜索结构中的成员并打印所有成员?
- 添加一个学生
- 查看所有的学生
- 搜索一个学生和出口
与结构的使用。该计划应该像学生的门户一样行事。 我有这个'暂定代码',当编译时,会打印一个错误的分段错误(核心转储)。所以这是我的代码怎么一回事:
#include<stdio.h>
typedef struct tag1{
int day, year, month;
}Date;
typedef struct tag2{
int number;
char name[50];
char course[30];
Date birthday;
}Record;
main(){
int choice, n, i=0;
Record student[200];
//printing of menu:
printf("Choose from the menu:\n");
printf(" [1] Add Student\n");
printf(" [2] Search Student\n");
printf(" [3] View All\n");
printf(" [4] Exit\n");
scanf("%d", &choice);
if((choice>=1)&&(choice<=4)){
if(choice==1){
printf("Enter student number:\n");
scanf("%d", &student[n].number);
printf("Enter the name of the student:\n");
scanf("%[^\n]", student[n].name);
printf("Enter month of birth:\n");
scanf("%d", &student[n].birthday.month);
printf("Enter day of birth:\n");
scanf("%d", &student[n].birthday.day);
printf("Enter year of birth:\n");
scanf("%d", &student[n].birthday.year);
printf("Enter course:\n");
scanf("%[^\n]", student[n].course);
n++;
}
if(choice==2){
while(i<n){
printf("%d\n", student[n].number);
printf("%s", student[n].name);
printf("%d/%d/%d", student[n].birthday.month, student[n].birthday.day,student[n].birthday.year);
printf("%s", student[n].course);
i++;
}
}
}
}
我只是中途因为我有我将如何为学生寻找不知道。希望你对我有任何改进我的代码的建议。
答
你忘了初始化n(你可能想要n = 0)。
答
假设,您使用i
迭代学生,直到达到第n个元素。
所以应该student[i]
不student[n]
这应该工作:
//...
while(i<n){
Record current = student[i];
printf("%d\n", current.number);
printf("%s", current.name);
printf("%d/%d/%d", current.birthday.month,
current.birthday.day,
current.birthday.year);
printf("%s", current.course);
i++;
}
是的,正应被初始化为0。
答
* 要secrh的学生,你可以使用像这样*
int sno;
unsigned char flag=0;
printf("Enter student number to search :");
scanf("%d",&sno);
然后搜索此记录到所有记录,当它匹配任何记录时,显示该记录。
for(i=0;i<n;i++) // where n is maximum number of records
{
if(student[i].number == sno)
{
flag=1;
/*** print all the member of student[i] ****/
break;
}
} // end of for loop
if(0==flag) { printf("\nSorry !!! Record not found with student number : %d\n",sno); }
段错误发生在哪里?你可以运行调试器来找出答案吗? – Floris 2013-03-10 04:50:41