2.循环与计数
通过while和if来构造输出*形框
const std::string::size_type cols=greeting.size() + pad*2+2
std::string将size_type定义成一个记录字符串的字符个数的类型,用这个类型 声明 cols为字符串中的字符个数
这个矩阵是这样构造的:
设定好pad表示填白是多少格。最终rows=pad*2+1+2表示最终多少行。
*********************
* *
* *
* *
* hello,cheng! *
* *
* *
* *
*********************
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "This is a project:became a cpp master less than one month" << endl;
cout << "type in your name:\n";
string name;
cin >> name;
const string greeting = " hello," + name + "!";
int pad = 3;
int rows = 2 * pad + 3;
int cols = greeting.size() + 2 * pad + 2;
for (int r = 0; r != rows; ++r)
{
int c = 0;
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 << '*';
else
cout << ' ';
++c;
}
}
cout << endl;
}
getchar();
getchar();
return 0;
}