C语言基础学习(13)malloc结构数组

动态(malloc【包含在<stdlib.h>文件】)建立结构数组,记得free建立的指针

/**   filmls.c  -- 使用一个结构数组    */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 2
char * s_gets(char*, int);
struct file
{
    char title[10];
    int rating;

};

int main()
{
    int i = 0;
    int n;
    struct file * movies;
    printf("Enter the space of max movie:\n");
    scanf("%d", &n);
    while(getchar() != '\n')
        continue;
    movies = (struct file *)malloc(n * sizeof(struct file));
    //puts("12");
    int j;
    puts("Enter a movie name:");
    while( i < n && s_gets(movies[i].title, 4) != NULL && movies[i].title != '\0' )
    {
        puts("Your rating <0-10>:");
        scanf("%d", &movies[i++].rating);
        while(getchar() != '\n')
            continue;
        puts("Enter next movie name(Empty to stop):");
    }
    if(i == 0)
        puts("No movies data.");
    else
        for(j = 0; j < i; j++)
    {
        printf("name: %s    rating: %d\n", movies[j].title, movies[j].rating);
    }
    puts("Bye !");

    free(movies);
    return 0;
}
char * s_gets( char* st, int n)
{
    char * rel_val;
    int i = 0;
    //puts("Enter your string");
    rel_val = fgets(st, n, stdin);
    if(rel_val)
    {
      while(st[i] != '\0' && st[i] != '\n')
        i++;
      if(st[i] == '\n')
        st[i] = '\0';
      else
        while(getchar() != '\n')
        continue;

    }
    //printf("rel_val:%s\n", rel_val);
    return rel_val;
}
scanf("%d", &n);
while(getchar() != '\n')
    continue;

使用 scanf 时候要记得,输入的是:number + ‘\n’,所以scanf读取数字后还剩‘\n’在输入端,所以要加while(getchar() != ‘\n’;contiune;进行清除

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值