C Primer Plus(第六版)17.12 编程练习 第1题 第一种方法

/* films2.c -- using a linked list of structures */

#include <stdio.h>

#include <stdlib.h> /* has the malloc prototype */

#include <string.h> /* has the strcpy prototype */

#define TSIZE 45 /* size of array to hold title */

struct film {

struct film * last; /* points to last struct in list */

char titleTSIZE;

int rating;

struct film * next; /* points to next struct in list */

};

char * s_gets(char * st, int n);

int main(void)

{

struct film * head = NULL;

struct film * end = NULL;

struct film * prev, * current;

char inputTSIZE;

/* Gather and store information */

puts("Enter first movie title:");

while (s_gets(input, TSIZE) != NULL && input0 != '\0')

{

current = (struct film *) malloc(sizeof(struct film));

if (head == NULL) /* first structure */

{

head = current;

head->last = NULL;

}

else /* subsequent structures */

{

prev->next = current;

current->last = prev;

}

current->next = NULL;

strcpy(current->title, input);

puts("Enter your rating <0-10>:");

scanf("%d", &current->rating);

while(getchar() != '\n')

continue;

puts("Enter next movie title (empty line to stop):");

prev = current;

end = current;

}

/* Show list of movies */

if (head == NULL)

printf("No data entered. ");

else

printf ("Here is the movie Positive sequence list:\n");

current = head;

while (current != NULL)

{

printf("Movie: %s Rating: %d\n",

current->title, current->rating);

current = current->next;

}

if (head == NULL)

printf("No data entered. ");

else

printf ("Here is the movie inverted sequence list:\n");

current = end;

while (current != NULL)

{

printf("Movie: %s Rating: %d\n",

current->title, current->rating);

current = current->last;

}

/* Program done, so free allocated memory */

current = head;

while (current != NULL)

{

free(current);

current = current->next;

}

printf("Bye!\n");

return 0;

}

char * s_gets(char * st, int n)

{

char * ret_val;

char * find;

ret_val = fgets(st, n, stdin);

if (ret_val)

{

find = strchr(st, '\n'); // look for newline

if (find) // if the address is not NULL,

*find = '\0'; // place a null character there

else

while (getchar() != '\n')

continue; // dispose of rest of line

}

return ret_val;

}

相关推荐
甄同学1 分钟前
第十七篇:Bash Executor命令执行器,安全运行Shell命令
开发语言·安全·bash
张3232 分钟前
Go语言基础 Map 函数值 闭包
开发语言·golang
杜子不疼.22 分钟前
【C++ 在线五子棋对战】- 会话管理模块实现
开发语言·c++
有点。26 分钟前
C++深度优先搜索(DFS)的概念(一)
开发语言·c++·深度优先
时间的拾荒人32 分钟前
C语言编译与链接:从源码到可执行程序的完整解析
c语言·开发语言
人道领域33 分钟前
【0-1的agent进阶篇】Prompt 与上下文工程
java·开发语言·prompt·mcp
aaPIXa62235 分钟前
C++大型项目模块化拆分实战记录
开发语言·c++
z落落37 分钟前
C# WinForm 线程池与事件等待+进度条暂停恢复实战案例
开发语言·c#
石山代码43 分钟前
C++23 新特性在 CLion 中的实战体验
开发语言·c++·c++23
浮江雾43 分钟前
Flutter第四节------核心概念学习笔记:从基础语法到异步编程
linux·服务器·开发语言·笔记·flutter·入门·基础