其他分享
首页 > 其他分享> > 30.有趣的例子(输入电影名称,并打分)

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;
}

 

标签:title,int,30,find,char,movies,str,有趣,打分
来源: https://www.cnblogs.com/bajiaotai/p/15163045.html