动态(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;进行清除