簡體   English   中英

我如何在C結構中搜索成員並打印所有成員?

[英]how can i search a member in a structure in C and print all the members?

我們被要求用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++;
            }
        }
        }


    }

我剛剛完成一半,因為我不知道如何尋找學生。 希望您對我有任何改進我的代碼的建議。

假設,您使用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。

您忘記了初始化n(您可能希望n = 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); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM