IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> C++知识库 -> C Primer Plus 第13章_代码和练习题 -> 正文阅读

[C++知识库]C Primer Plus 第13章_代码和练习题

14.1 示例问题:创建图书目录

处理一本书, 书名-作者-价格, 输入输出
book.c–一本书的图书目录
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* s_gets(char* st, int n);
#define MAXTITL 41              			/* 书名的最大长度 + 1 */
#define MAXAUTL 31							/* 作者姓名的最大长度 + 1 */

/* 设计程序时,最重要的步骤之一是表示数据的方法 */

/* 建立结构声明 */
struct book {								// 结构模板: 标记是book
	char title[MAXTITL];
	char author[MAXAUTL];
	float value;
};

int main(void)
{
	struct book library;					// 定义结构变量

	printf("Please enter the book title.\n");
	s_gets(library.title, MAXTITL);

	printf("Now enter the author.\n");
	s_gets(library.author, MAXAUTL);

	printf("Now enter the value.\n");
	scanf("%f", &library.value);

	printf("%s by %s: $%.2f\n", library.title, library.author, library.value);
	printf("%s: \"%s\" ($%.2f)\n", library.title, library.author, library.value);
	printf("Done.\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');			// 查找换行符

		if (find) {							// 如果地址不是NULL
			*find = '\0';					// 在此处放置一个空字符
		}
		else {
			while (getchar() != '\n')		// 处理输入行中剩余的字符
			{
				continue;
			}
		}
	}
	return ret_val;
}

14.2 结构数组

处理多本书,输入输出。
manybook.c–包含多本书的图书目录
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* s_gets(char* st, int n);
#define MAXTITL 41
#define MAXAUTL 31
#define MAXBKS 100								// 书籍的最大数量

struct book {
	char title[MAXTITL];
	char author[MAXAUTL];
	float value;
};

int main(void)
{
	struct book library[MAXBKS];					// book类型结构的数组
	int count = 0;
	int index;

	printf("Please enter the book title.\n");
	printf("Press [enter] at the start of a line to stop.\n");
	
	/* 表达式library[count].title[0] != '\0'判断字符串中的首字符是否是空字符(即该字符串是否是空字符串) */
	while (count < MAXBKS && s_gets(library[count].title, MAXTITL) != NULL
		&& library[count].title[0] != '\0') 
	{
		printf("Now enter the author.\n");
		s_gets(library[count].author, MAXAUTL);

		printf("Now enter the value.\n");
		scanf("%f", &library[count++].value);
		while (getchar() != '\n') {
			continue;								// 清理输入行
		}
		if (count < MAXBKS) {
			printf("Enter the next title.\n");
		}
	}

	if (count > 0) {
		printf("Here is the list of your books:\n");
		for (index = 0; index < count; index++) {
			printf("%s by %s: $%.2f\n", library[index].title, 
				library[index].author, library[index].value);
		}
	}
	else {
		printf("No books? Too bad.\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');			// 查找换行符

		if (find) {							// 如果地址不是NULL
			*find = '\0';					// 在此处放置一个空字符
		}
		else {
			while (getchar() != '\n')		// 处理输入行中剩余的字符
			{
				continue;
			}
		}
	}
	return ret_val;
}

14.5 嵌套结构

在一个结构中包含另一个结构(即嵌套结构)很方便。
friend.c–嵌套结构示例
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define LEN 20

const char* msgs[5] = {
	"	Thank you for the wonderful evening, ",
	"You certainly prove that a ",
	"is a special kind of guy. We must get together",
	"over a delicious ",
	" and have a few laughs"
};

struct name {
	char first[LEN];
	char last[LEN];
};

struct guy {
	struct name handle;
	char favfood[LEN];
	char job[LEN];
	float income;
};

int main(void)
{
	struct guy fellows = {
		{"Ewen" , "Villard"},
		"grilled salmon",
		"personality coach",
		68112.00
	};

	printf("Dear %s,\n\n", fellows.handle.first);
	printf("%s%s.\n", msgs[0], fellows.handle.first);
	printf("%s%s\n", msgs[1], fellows.job);
	printf("%s\n", msgs[2]);
	printf("%s%s%s", msgs[3], fellows.favfood, msgs[4]);
	if (fellows.income > 1500000.0f) {
		printf("!!");
	}
	else if (fellows.income > 75000.0f) {
		printf("!");
	}
	else {
		printf(".");
	}

	printf("\n%40s%s\n", " ", "See you soon,");
	printf("%40s%s\n", " ", "Shalala");

	return 0;
}

14.6 指向结构的指针

演示:如何定义指向结构的指针和如何用这样的指针访问结构的成员
friends.c–使用指向结构的指针在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>

#define LEN 20

struct name {
	char first[LEN];
	char last[LEN];
};

struct guy {
	struct name handle;
	char favfood[LEN];
	char job[LEN];
	float income;
};

int main(void)
{
	struct guy fellows[2] = {
		{
			{"Ewen", "Villard"},
			"grilled salmon",
			"personality coach",
			68112.00
		},
		{
			{"Rodney", "Swillbelly"},
			"tripe",
			"tabloid editor",
			432400.00
		}
	};

	struct guy* him;

	printf("address #1: %p #2: %p\n", &fellows[0], &fellows[1]);
	him = &fellows[0];
	printf("address #1: %p #2: %p\n", him, him + 1);
	printf("him->income is $%.2f: (*him).income is $%.2f\n", him->income, (*him).income);
	him++;
	printf("him->favfood is %s: (*him).favfood is %s\n", him->favfood, (*him).favfood);

	return 0;
}

14.7 向函数传递结构的信息

传递结构成员

funds.c–把结构成员作为参数传递

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>

#define FUNDLEN 50

struct funds {
	char bank[FUNDLEN];
	double bankfund;
	char save[FUNDLEN];
	double savefund;
};

double sum(double x, double y);

int main(void)
{
	struct funds stan = {
		"Garlic-Melon Bank",
		4032.27,
		"Lucky's Saving and Loan",
		8543.94
	};

	printf("Stan has a total of $%.2f.\n", 
		sum(stan.bankfund, stan.savefund));

	return 0;
}

double sum(double x, double y)
{
	return (x + y);
}

传递结构地址

funds2.c–传递指向结构的指针

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>

#define FUNDLEN 50

struct funds {
	char bank[FUNDLEN];
	double bankfund;
	char save[FUNDLEN];
	double savefund;
};

double sum(const struct funds*);    // 参数是一个指针

int main(void)
{
	struct funds stan = {
		"Garlic-Melon Bank",
		4032.27,
		"Lucky's Saving and Loan",
		8543.94
	};

	printf("Stan has a total of $%.2f.\n", 
		sum(&stan));

	return 0;
}

double sum(const struct funds *money)
{
	return (money->bankfund + money->savefund);
}

传递结构

funds3.c–传递一个结构

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>

#define FUNDLEN 50

struct funds {
	char bank[FUNDLEN];
	double bankfund;
	char save[FUNDLEN];
	double savefund;
};

double sum(struct funds moolah);    // 参数是一个结构

int main(void)
{
	struct funds stan = {
		"Garlic-Melon Bank",
		4032.27,
		"Lucky's Saving and Loan",
		8543.94
	};

	printf("Stan has a total of $%.2f.\n", sum(stan));

	return 0;
}

double sum( struct funds moolah)
{
	return (moolah.bankfund + moolah.savefund);
}

14.7.4 其它结构特性

names1.c–使用指向结构的指针
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#define NLEN 30
struct namect {
	char fname[NLEN];
	char lname[NLEN];
	int letters;
};

void getinfo(struct namect *);
void makeinfo(struct namect *);
void showinfo(const struct namect *);
char* s_gets(char* st, int n);

int main(void)
{
	struct namect person;

	getinfo(&person);
	makeinfo(&person);
	showinfo(&person);

	return 0;
}

void getinfo(struct namect* pst)
{
	printf("Please enter your first name.\n");
	s_gets(pst->fname, NLEN);
	printf("Please enter your last name.\n");
	s_gets(pst->lname, NLEN);
}

void makeinfo(struct namect* pst)
{
	pst->letters = strlen(pst->fname) + strlen(pst->lname);
}

void showinfo(const struct namect* pst)
{
	printf("%s %s, your name contains %d letters.\n", 
				pst->fname, pst->lname, pst->letters);
}

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');
		if (find) {
			*find = '\0';
		}
		else {
			while (getchar() != '\n') {
				continue;
			}
		}
	}
	return ret_val;
}

如何使用结构参数和返回来完成相同的任务

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

#define NLEN 30
struct namect {
	char fname[NLEN];
	char lname[NLEN];
	int letters;
};

struct namect getinfo(void);
struct namect makeinfo(struct namect );
void showinfo(struct namect);
char* s_gets(char* st, int n);

int main(void)
{
	struct namect person;

	person = getinfo();
	person = makeinfo(person);
	showinfo(person);

	return 0;
}

struct namect getinfo(void)
{
	struct namect temp;

	printf("Please enter your first name.\n");
	s_gets(temp.fname, NLEN);
	printf("Please enter your last name.\n");
	s_gets(temp.lname, NLEN);

	return temp;
}

struct namect makeinfo(struct namect info)
{
	info.letters = strlen(info.fname) + strlen(info.lname);

	return info;
}

void showinfo(const struct namect info)
{
	printf("%s %s, your name contains %d letters.\n", 
		info.fname, info.lname, info.letters);
}

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');
		if (find) {
			*find = '\0';
		}
		else {
			while (getchar() != '\n') {
				continue;
			}
		}
	}
	return ret_val;
}

14.7.7 结构、指针和malloc()

name3.c–使用指针和malloc()
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SLEN 81

struct namect {
	char * fname;
	char * lname;
	int letters;
};

void getinfo(struct namect *);
void makeinfo(struct namect *);
void showinfo(const struct namect *);
char* s_gets(char* st, int n);
void cleanup(struct namect*);

int main(void)
{
	struct namect person;

	getinfo(&person);
	makeinfo(&person);
	showinfo(&person);

	return 0;
}

void getinfo(struct namect * pst)
{
	char temp[SLEN];
	
	printf("Please enter your first name.\n");
	s_gets(temp, SLEN);
	// 分配内存以储存名
	pst->fname = (char*)malloc(strlen(temp) + 1);
	// 把名拷贝到动态分配的内存中
	strcpy(pst->fname, temp);

	printf("Please enter your last name.\n");
	s_gets(temp, SLEN);
	pst->lname = (char*)malloc(strlen(temp) + 1);
	strcpy(pst->lname, temp);

}

void makeinfo(struct namect * info)
{
	info->letters = strlen(info->fname) + strlen(info->lname);
}

void showinfo(const struct namect * info)
{
	printf("%s %s, your name contains %d letters.\n", 
		info->fname, info->lname, info->letters);
}

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');
		if (find) {
			*find = '\0';
		}
		else {
			while (getchar() != '\n') {
				continue;
			}
		}
	}
	return ret_val;
}

void cleanup(struct namect* pst)
{
	free(pst->fname);
	free(pst->lname);
}

14.7.8 复合字面量和结构

complit.c–复合字面量

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXTITL 41
#define MAXAUTL 31

struct book {
	char title[MAXTITL];
	char author[MAXAUTL];
	float value;
};

int main(void)
{
	struct book readfirst;
	int score;

	printf("Enter test score: ");
	scanf("%d", &score);

	if (score >= 84) {
		readfirst = (struct book){ "Crime and Punishment",
									"Fyodor Dostoyevsky",
									12.25f };
	}
	else {
		readfirst = (struct book){ "Mr. Bouncy's Nice Hat",
									"Fred Winsome",
									5.99f };	
	}

	printf("Your assigned reading:\n");
	printf("%s by %s: $%.2f\n", readfirst.title,
		readfirst.author, readfirst.value);

	return 0;
}

14.7.11 使用结构数组的函数

funds4.c–把结构数组传递给函数

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FUNDLEN 50
#define N 2

struct funds {
	char bank[FUNDLEN];
	double bankfunds;
	char save[FUNDLEN];
	double savefunds;
};

double sum(const struct funds money[], int n);

int main(void)
{
	struct funds jones[N] = {
		{
			"Garlic-Melon Bank",
			4032.27,
			"Lucky's Savings and Loan",
			8543.94,
		},
		{
			"Honest Jack's Bank",
			3620.88,
			"Party Time Savings",
			3802.91,
		}
	};

	printf("The Jones have a total of $%.2f.\n", sum(jones, N));

	return 0;
}

double sum(const struct funds money[], int n)
{
	double total;
	int i;

	for (i = 0, total = 0; i < n; i++) {
		total += money[i].bankfunds + money[i].savefunds;
	}

	return (total);
}

14.8 把结构内容保存到文件中

使用fread()和fwrite()函数读写结构大小的单元
保存结构的程序示例
把书名保存到book.dat文件中,如果该文件已经存在,程序将显示它当前的内容,然后允许在文件中添加内容。
booksave.c–在文件中保存结构中的内容


14.11.4 enum的用法

enum.c–使用枚举类型的值
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* s_gets(char* st, int n);
enum spectrum {red, orange, yellow, green, blue, violet};
const char* colors[] = { "red", "orange", "yellow", "green", "blue", "violet" };
#define LEN 30

int main(void)
{
	char choice[LEN];
	enum spectrum color;
	bool color_is_found = false;

	puts("Enter a color (enter line to quit):");
	while (s_gets(choice, LEN) != NULL && choice[0] != '\0') {
		for (color = red; color <= violet; color++) {
			if (strcmp(choice, colors[color]) == 0) {
				color_is_found = true;
				break;
			}
		}
		if (color_is_found) {
			switch (color) {
			case red:			puts("Rose are red.");
				break;
			case orange:		puts("Poppies are orange.");
				break;
			case yellow:		puts("Sunflowers are yellow.");
				break;
			case green:			puts("Grass is green.");
				break;
			case blue:			puts("Blubells are blue.");
				break;
			case violet:		puts("Violets are violet.");
				break;
			}
		}
		else {
			printf("I don't know about the color %s.\n", choice);
		}

		color_is_found = false;
		puts("Nest color, please (empty line to quit):");

	}

	puts("Goodbye!");

	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');
		if (find) {
			*find = '\0';
		}
		else {
			while (getchar() != '\0') {
				continue;
			}
		}
	}
	return ret_val;
}

14.14 函数和指针

func_ptr.c–使用函数指针
在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define LEN 81

char* s_gets(char* st, int n);
char showmenu(void);
void eatline(void);					// 读取至行末尾
void show(void(*fp)(char*), char* str);
void ToUpper(char*);				// 把字符串转化为大写
void ToLower(char*);				// 把字符串转化为小写
void Transpose(char*);				// 大小写转置
void Dummy(char*);					// 不更改字符串

int main(void)
{
	char line[LEN];
	char copy[LEN];
	char choice;
	void (*pfun)(char*) = NULL;	//声明一个函数指针,被指向的函数接受char*类型的参数,无返回值

	puts("Enter a string (empty line to quit):");
	while (s_gets(line, LEN) != NULL && line[0] != '\0') {
		while ((choice = showmenu()) != 'n') {
			switch (choice) {
			case 'u': pfun = ToUpper; break;
			case 'l': pfun = ToLower; break;
			case 't': pfun = Transpose; break;
			case 'o': pfun = Dummy; break;
			}
			strcpy(copy, line);				// 为show()函数拷贝一份
			show(pfun, copy);				// 根据用户的选择,使用选定的函数
		}
		puts("Enter a string (empty line to quit):");
	}
	puts("Bye!");

	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');
		if (find) {
			*find = '\0';
		}
		else {
			while (getchar() != '\0') {
				continue;
			}
		}
	}
	return ret_val;
}

char showmenu(void)
{
	char ans;
	puts("Enter menu choice:");
	puts("u) uppercase			l) lowercase");
	puts("t) transposed case    o) original case");
	puts("n) next string");
	
	ans = getchar();				// 获取用户的输入
	ans = tolower(ans);				// 转换为小写
	eatline();						// 清理输入行
	while (strchr("ulton", ans) == NULL) {
		puts("Please enter a u, l, t, o, or n:");
		ans = tolower(getchar());
		eatline();
	}
	return ans;
}

void eatline(void)					// 读取至行末尾
{
	while (getchar() != '\n') {
		continue;
	}
}

void show(void(*fp)(char*), char* str)
{
	(*fp)(str);							// 把用户选定的函数作用于str
	puts(str);							// 显示结果
}

void ToUpper(char* str)					// 把字符串转化为大写
{
	while(*str) {
		*str = toupper(*str);
		str++;
	}
}

void ToLower(char* str)					// 把字符串转化为小写
{
	while(*str) {
		*str = tolower(*str);
		str++;
	}
}
	

void Transpose(char* str)				// 大小写转置
{
	while(*str) {
		if (islower(*str)) {
			*str = toupper(*str);
		}
		else if(isupper(*str)) {
			*str = tolower(*str);
		}
		str++;
	}
}


void Dummy(char* str)					// 不更改字符串
{

}

  C++知识库 最新文章
【C++】友元、嵌套类、异常、RTTI、类型转换
通讯录的思路与实现(C语言)
C++PrimerPlus 第七章 函数-C++的编程模块(
Problem C: 算法9-9~9-12:平衡二叉树的基本
MSVC C++ UTF-8编程
C++进阶 多态原理
简单string类c++实现
我的年度总结
【C语言】以深厚地基筑伟岸高楼-基础篇(六
c语言常见错误合集
上一篇文章      下一篇文章      查看所有文章
加:2022-06-14 22:19:58  更:2022-06-14 22:20:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 17:02:01-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码