结构数组
/** filmls.c -- 使用一个结构数组 */
#include<stdio.h>
#include<string.h>
#define TSIZE 45 //储存片名数组大小
#define FMAX 2 //影片最大数量
struct film{
char title[TSIZE];
int rating;
};
char * s_gets(char str[], int);
int main(void)
{
struct film movies[TSIZE];
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);
printf("%d\n", i);
while(getchar()!= '\n')
continue;
puts("Enter next movie title(or empty line to stop):");
}
if( i == 0)
printf("No data enter. ");
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 * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
//printf(("%c \n", ret_val));
if(ret_val)
{
while(st[i] != '\n' && st[i] != '\0')
i++;
if(st[i] == '\n')
st[i] = '\0';
else
while(getchar() != '\n')
continue;
}
return ret_val;
}
结构链表
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char * s_gets(char*, int);
struct file
{
char title[10];
int rating;
char * next;
};
int main()
{
struct file * head = NULL;
struct file *prev, * current;
char input[10];
/** 储存数组 */
puts("Enter a movie name:");
while(s_gets(input, 10) != NULL && input[0] != '\0')
{
current = (struct file *) malloc(sizeof(struct file));
if(head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy(current->title, input);
puts("Enter your rating:");
scanf("%d", ¤t->rating);
while(getchar() != '\n')
continue;
puts("Input the next movie name:");
prev = current;
}
/** 显示电影列表 */
if(head == NULL)
printf("No data entered!\n");
else
printf("There is a movies list: \n");
current = head;
while(current != NULL)
{
printf("Movie : %s Rating: %d \n",
current->title, current->rating);
current = current->next;
}
/** 释放内存 */
current = head;
while(current != NULL)
{
current = head;
head = current->next;
free(current);
}
puts("Bye !");
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;
}
char* head;赋值给current时指针类型不一样
应该把head也改成struct file *类型