30.有趣的例子(输入电影名称,并打分)

/* filems1.c -- 使用一个结构数组 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TSIZE 45 //定义存储电影名称数组的大小

//定义电影struct
struct film
{
    char title[TSIZE];
    int rating; 
};

char * s_gets(char str[], int lim);

int main(void)
{
  struct film * movies;
  int i = 0;
  int j;
  int n;
  puts("Enter the maximum number of movies you'll enter:");
  scanf("%d",&n);
  //n = 3;
  fpurge(stdin);//清除input stream
  movies = (struct film *) malloc(n * sizeof(struct film));
  puts("Enter first movie title:");
  //循环填下电影名称和评分
  while(i < n && s_gets(movies[i].title,TSIZE) != NULL && movies[i].title[0] != '\0')
  {
      puts("Enter your rating <0-10>:");
      scanf("%d",&movies[i++].rating);
      while(getchar() != '\n')
        continue;
      puts("Enter next movie title (empty line to stop):");
  }
  if (i == 0)
      printf("No data entered.");
  else
      printf("Here is the movie list:\n" );

  for (j = 0; j < i; j++)
      printf("Movie: %s Rating: %d\n", movies[j].title, movies[j].rating);
  printf("Bye!\n" );

  return 0;
}

char * s_gets(char str[], int lim)
{
    char * ret_val;
    char * find;

    ret_val = fgets(str,lim, stdin);

    if (ret_val)
    {
        find = strchr(str, '\n');
        if (find)
            *find = '\0';
        // else
        //     while (getchar() != '\n')
        //         continue;
    }
    return ret_val;
}

/*
这个案例的启示:
1.fgets 函数
  char *fgets(char *str, int n, FILE *stream)
  作用:将键盘输入存储的指定数组中
  返回值:char * = char *str;



*/

-- 非动态数组

/* filems1.c -- 使用一个结构数组 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TSIZE 45 //定义存储电影名称数组的大小
#define FMAX  5  //定义存储电影的数量

//定义电影struct
struct film
{
    char title[TSIZE];
    int rating; 
};

char * s_gets(char str[], int lim);

int main(void)
{
  struct film movies[FMAX];
  int i = 0;
  int j;
  puts("Enter first movie title:");
  while(i < FMAX && s_gets(movies[i].title,TSIZE) != NULL && movies[i].title[0] != '\0')
  {
      puts("Enter your rating <0-10>:");
      scanf("%d",&movies[i++].rating);
      while(getchar() != '\n')
        continue;
      puts("Enter next movie title (empty line to stop):");
  }
  if (i == 0)
      printf("No data entered.");
  else
      printf("Here is the movie list:\n" );

  for (j = 0; j < i; j++)
      printf("Movie: %s Rating: %d\n", movies[j].title, movies[j].rating);
  printf("Bye!\n" );

  return 0;
}

char * s_gets(char str[], int lim)
{
    char * ret_val;
    char * find;

    ret_val = fgets(str,lim, stdin);
    if (ret_val)
    {
        find = strchr(str, '\n');
        printf("%p\n", find );
        if (find)
            *find = '\0';
        // else
        //     while (getchar() != '\n')
        //         continue;
    }
    return ret_val;
}

 

上一篇:电影节


下一篇:2021-11-20:一场电影开始和结束时间可以用一个小数组来表示[“07:30“,“12:00“],已知有2000场电影开始和结束都在同一天,这一天从00:00开始到23:59结束,一定要选3场完全