1. 程式人生 > >《程式設計珠璣》程式碼之路6:將邏輯和程式碼分離----編碼形式圖形化輸出字母

《程式設計珠璣》程式碼之路6:將邏輯和程式碼分離----編碼形式圖形化輸出字母

好啦比如字母I,輸出為:

xxxxxxxxx
xxxxxxxxx
xxxxxxxxx
     xxx     
     xxx     
     xxx     
     xxx     
     xxx     
     xxx     
xxxxxxxxx
xxxxxxxxx
xxxxxxxxx

字母L輸出為:

xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx

看到這裡,好多人說這不很簡單嗎,我一堆for迴圈,不就出迴圈輸出空格和x嘛。對的,沒錯我剛開始也這麼想。

於是乎,每次要改變點什麼就得改程式碼。

其實可以這樣,I其實可以表示成這樣

3 9 x 
6 5 b 3 x 5 b 
3 9 x 

代表這個意思:

3行:9個x

6行:5個空格,3個x,5個空格

3行:9個x

然後再寫個解析函式,這樣的話,每次只需要改上述描述就可以了:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int main(){
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);

	char str[100];
	char *p = str;
	int line, num;
	char c;

	while (NULL != gets(str)){
		p = str;
		sscanf(p, "%d", &line);
		//cout << line << ' ';
		for (int i = 0; i < line; ++i){
			p = str + 2;
			int len = strlen(p) / 4;
			while (sscanf(p, "%d %c", &num, &c) && len > 0){
				//cout << num << ' ' << c << ' ';
				for (int j = 0; j < num; ++j){
					if (c == 'b'){
						cout << " ";
					}else{
						cout << c;
					}
				}
				p += 4;
				len--;
			}
			cout << endl;
		}

		//cout << endl;
	}

	return 0;
}