1. 程式人生 > >Accelerated C++學習筆記3—

Accelerated C++學習筆記3—

<span style="font-family:KaiTi_GB2312;">// lesson2_2.cpp : 定義控制檯應用程式的入口點。
//功能:改寫程式碼,程式每次一個字元地輸出了大部分的空白行;且讓使用者自己提供在框架和問候語之間的空格個數
//時間:2014.5.8

#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	//請求使用者輸入姓名
	cout << "Please enter your first name:: ";

	//讀入使用者輸入的姓名
	string name;
	cin >> name;
	
	//請求使用者輸入圍住問候語的空白個數
	cout << "Please enter the space size:: ";
	int pad;
	cin >> pad;

	//構造我們將要輸出的資訊
	const string greeting = "Hello, " + name + "!";

	//圍住問候語的空白個數
	//const int pad = 1;

	//待輸出的行數與列數
	const int rows = pad * 2 + 3;
	const string::size_type cols = greeting.size() + pad * 2 + 2;
	const string spaces = string(greeting.size() + pad * 2, ' ');

	//輸出一個空白行,把輸出與輸入分隔開
	cout << endl;

	//輸出rows行
	//不變式:到目前為止,我們已經輸出了r行
	for(int r = 0; r != rows; ++r)
	{
		string::size_type c = 0;

		//不變式:到目前為止,在當前行中我們已經輸出c個字元
		while (c != cols)
		{
			//應該輸出問候語了嗎?
			if(r == pad + 1 && c == pad + 1)
			{
				cout << greeting;
				c += greeting.size();
			}
			else 
			{
				//我們是位於邊界上嗎?
				if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1)
				{
					cout << "*";
					++c;
				}
				else if (r == pad + 1)
				{
					cout << " ";	
					++c;
				}
				else 
				{
					cout << spaces;
					c += spaces.size();
				}
			}
		}

		cout << endl;
	}

	return 0;
}

</span>

執行結果: