1. 程式人生 > >《程式設計珠璣》程式碼之路5:格式信函程式設計----將資料和程式碼分開的好處

《程式設計珠璣》程式碼之路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;
}