C语言数据结构调取学生信息

直接上代码,这个项目通俗易懂。

#include <stdio.h>
#include <string.h>
#define NAME_LEN 40
#include <assert.h>
typedef struct {
    char name[NAME_LEN];
    unsigned int id;
    float shoe_size;
}Student;

Student new_student(const char name[], unsigned int id, float shoe_size){
  /*create student struct variable*/
  Student student;
  
  /*storing infor into structure*/
    if(name == NULL)
      strcpy(student.name, "");
  
    if(name != NULL && strlen(name) > 39)
    {
      strncpy(student.name, name, 39);
      student.name[39]= '\0';
    }
    
    if(name != NULL && strlen(name) < 39)
    strcpy(student.name, name);
    student.id= id;
    student.shoe_size= shoe_size;
  /*return a new stucture */
    return student;
}

void init_student(Student *const student, const char name[], unsigned int id,
                  float shoe_size){
    if(student == NULL)
        return;
    if(name == NULL)
        strcpy(student -> name, "");
    else
    strcpy(student -> name, name);
    student -> id= id;
    student -> shoe_size= shoe_size;
}

unsigned int has_id(Student student, unsigned int id){
  if(student.id != id)
    return 0;
  return 1;
}

unsigned int has_name(Student student, const char name[]){
  int a= 0;
  if(name == NULL)
      return 0;
  a= strcmp(student.name, name);
  
  if(a != 0)
      return 0;
  return 1;
}

unsigned int get_id(Student student){
  return student.id;
}

float get_shoe_size(Student student){
return student.shoe_size;
}

Student change_shoe_size(Student student, float new_shoe_size){
  student.shoe_size= new_shoe_size;
  return student;
}

void change_name(Student *const student, const char new_name[]){
    if(student == NULL)
        return;
    if(new_name == NULL){
        strcpy(student -> name, "");
        return;
    }
     if(strlen(new_name) > 39)
        {
          strncpy(student -> name, new_name, 39);
          strcat(student -> name, "\0");
        }
    strcpy(student -> name, new_name);
}
/*
int main(void) {
  Student s= new_student("Hao", 11111, 8.0);

  should return 0, and by the way not crash */
  /*
  assert(!has_name(s, NULL));
  assert(has_name(s, "Hao"));

  /* should set the student's name to an empty string, and not crash */
  /*change_name(&s, NULL);
  assert(has_name(s, ""));

  printf("Yes!\n");

  return 0;
}
*/
int main(void) {
  Student s= new_student("Penelope", 38463, 5.0);

  change_name(&s, "Penny");

  assert(has_id(s, 38463));
  assert(get_id(s) == 38463);
  assert(has_name(s, "Penny"));
  assert(get_shoe_size(s) == 5.0);

  printf("Yes!\n");

  return 0;
}







 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值