#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct film {
char title[45];
int rating;
struct file* next;
};
char* s_gets(char* st, int n);
int main(void)
{
struct film* head = NULL;
struct film* prev, * current;
char input[45];
puts("enter first name");
while (s_gets(input, 45) && input[0] != '\0') {
current = (struct film*)malloc(sizeof(struct film));
prev= (struct film*)malloc(sizeof(struct film));
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy_s(current->title,45,input);
puts("enter first rating");
scanf_s("%d", ¤t->rating);
while (getchar() != '\n')
continue;
puts("enter next");
prev = current;
}
if (head == NULL)
puts("there is no moive");
else
puts("there is a movie list");
current = head;
while (current != NULL) {
printf("%s ,%d", current->title, current->rating);
current = current->next;
}
current = head;
while (current != NULL) {
free(current);
head = current->next;
}
return 0;
}
char* s_gets(char* st, int n) {
char* ret_val;
char* find;
int i = 0;
ret_val = fgets(st, n, stdin);//下文所出現的都是已經輸入完成的內容
if (ret_val) {//fgets沒有讀取到檔案結尾或者讀取錯誤
find = strchr(st, '\n');
if (find)
{
*find = '\0';
}
else
while (getchar() != '\n')
continue;
}
return ret_val;
}

uj5u.com熱心網友回復:
記憶體泄露: while (current != NULL) {
free(current);
current = current->next;
}
uj5u.com熱心網友回復:
而且pre指標也不用分配空間,應該注釋掉//prev= (struct film*)malloc(sizeof(struct film));
uj5u.com熱心網友回復:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct film {
char title[45];
int rating;
struct file* next;
};
char* s_gets(char* st, int n);
int main(void)
{
struct film* head = NULL;
struct film* prev, * current;
char input[45];
puts("enter first name");
while (s_gets(input, 45) && input[0] != '\0') {
current = (struct film*)malloc(sizeof(struct film));
//prev= (struct film*)malloc(sizeof(struct film));
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy(current->title,input);
puts("enter first rating");
scanf("%d", ¤t->rating);
while (getchar() != '\n')
continue;
puts("enter next");
prev = current;
}
if (head == NULL)
puts("there is no moive");
else
puts("there is a movie list");
current = head;
while (current != NULL) {
printf("%s ,%d\n", current->title, current->rating);
current = current->next;
}
current = head;
while (current != NULL) {
free(current);
current = current->next;
}
return 0;
}
char* s_gets(char* st, int n) {
char* ret_val;
char* find;
int i = 0;
ret_val = fgets( st, n, stdin);//下文所出現的都是已經輸入完成的內容
if (ret_val) {//fgets沒有讀取到檔案結尾或者讀取錯誤
find = strchr(st, '\n');
if (find)
{
*find = '\0';
}
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/22480.html
標籤:C語言
下一篇:boost spirit求助
