《编程珠玑》代码之路5:格式信函编程----将数据和代码分开的好处

我们打开一些网站,经常会看到不同客户专属信息,例如:

Welcome back, Jane!
We hope that you and all the members
of the Public family are constantly
reminding your neighbers there
on Maple Street to shop with us.
As usuall, we will ship your order to
    Ms. Jane Q. Public
    600 Maple Street
    Your Town, Iowa 12345

.......

其中加黑部分来自于不同的用户,但模板都是一样的。

用户的字段是这样的,不同的用户会有不同的字段,但规格相同:

str[]= {"Public", "Jane", "Q", "Ms.", "600", "Maple Street", "Your Town", "Iowa", "12345"};

于是很多程序员就会这些撸代码:

以第一行为例:

printf("Welcome back")
printf("%s!", str[0]);

然后每一行都这么写一遍,可以想象,如果这时候团队的PM给了你个模板,你就在代码里把它敲了一遍,文档5000个字符你就得敲5000多个字符的代码,而且PM一旦把模板改了,又得再改一遍代码。不仅工作量大,还没啥意义,那么怎么办呢?

怎么做到模板改了,我还不用改代码呢?而且还的保证不懂技术的PM也方便。

看下面这个东西:

Welcome back, $1!
We hope that you and all the members
of the $0 family are constantly
reminding your neighbers there
on $5 to shop with us.
As usuall, we will ship your order to
    $3 $1 $2. $0
    $4 $5
    $6, $7 $8

.......

对了,用$x代表第x个信息,然后你随便改模板,我就写个解析函数,解析一下就可以了。

解析函数干什么呢,就是在上述约定的文档中,碰到模板字符,我直接输出就好了。碰到用户字段,我就输出相应的字段。这样,我就不用把文档里的字符都给敲一遍了,大家都方便。这就是数据和代码分开的好处。

解析函数如下:

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>

using namespace std;

//实际中这个字符串是从数据库读出来的
string str[] = {"Public", "Jane", "Q", "Ms.", "600", "Maple Street", "Your Town", "Iowa", "12345"};
vector<string> field(str, str + 10);

int main(){
    //这个文件指的是带有约定$的模板文档
	freopen("FormLetterSchema.txt", "r", stdin);
	freopen("out.txt", "w", stdout);

	char c;
	while (scanf("%c", &c) != EOF){

		if (c != '$'){
			printf("%c", c);
		}else{

			scanf("%c", &c);
			//如果在文本中本身就是$

			if (c == '$'){
				printf("$");
			}else{//否则输出相应的字段
				printf("%s", field[c - '0'].c_str());
			}

		}
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/beijixiong5622/article/details/84111118