我们被要求在c中编写一个能够使用户
的某个程序使用结构。该计划应该像学生的门户一样。 我有这个'暂定代码',在编译时会打印出Segmentation fault(core dumped)的错误。所以这就是我的代码:
#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++;
}
}
}
}
我只是一半,因为我不知道如何搜索学生。希望您有任何建议让我改进我的代码。
答案 0 :(得分:1)
假设您使用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++;
}
是的,n应初始化为0。
答案 1 :(得分:0)
你忘了初始化n(你可能想要n = 0)。
答案 2 :(得分:0)
* 对于学生来说,你可以像这样使用
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); }