分手信自动生成器
假设你在写一个群发邮件的程序,向不同人发送不同类型的消息,一种创建回复数据的方法是使用结构:
你将发送三种类型的回复,每条回复都要保存回复类型,回复类型用枚举表示。在使用新数据类型response
时需要根据回复类型分别调用以下三个函数:
- void dump(response r)
- {
- printf("Dear %s,\n", r.name);
- puts("Unfortunately your last date contacted us to");
- puts("say that they will not be seeing you again");
- }
- void second_chance(response r)
- {
- printf("Dear %s,\n", r.name);
- puts("Good news: your last date has asked us to");
- puts("arrange another meeting. Please call ASAP.");
- }
- void marriage(response r)
- {
- printf("Dear %s,\n", r.name);
- puts("Congratulations! Your last date has contacted");
- puts("us with a proposal of marriage.");
- }
你已经有了数据结构,生成回复的函数也有了,下面就来看看如何根据response
数组批量生成回复。
游泳池拼图
从游泳池中取出代码片段,放到下面的空白横线处。你的目标是拼凑出main()
函数,为response
数组批量生成邮件。每个片段最多只能使用一次。
游泳池拼图解答
从游泳池中取出代码片段,放到下面的空白横线处。你的目标是拼凑出main()
函数,为response
数组批量生成邮件。每个片段最多只能使用一次。
试驾
当运行程序时,程序果然为每个人都生成了相应的回复:
程序正确运行了,但代码中充斥着大量函数调用,每次都需要根据回复类型来调用函数,看起来像这样:
switch(r.type) {
case DUMP:
dump(r);
break;
case SECOND_CHANCE:
second_chance(r);
break;
default:
marriage(r);
}
如果增加第四种回复类型,你就不得不修改程序中每一个像这样的地方。很快,就有一大堆代码需要维护,而且这样很容易出错。
好在可以使用一个C语言的技巧,这个技巧涉及数组……