From《Accelerated C++》P29——
改写cout输出程序,利用双层循环打印。
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout<<"please enter your first name:";
string name;
cin>>name;
const string sentences="hello,"+name+"!";
const int pad=1;
const int rows=pad*2+3;
const <span style="color:#FF0000;">string::size_type cols</span>=pad*2+sentences.size()+2;
cout<<endl;
for(int r=0;r<rows;r++)
{
string::size_type c=0;
while(c!=cols)
{
if(r==pad+1&&c==pad+1)
{
cout<<sentences;
c+=sentences.size();
}
else{
if(r==0||c==0||r==rows-1||c==cols-1)
cout<<"*";
else
cout<<" ";
++c;
}
}
cout<<endl;
}
return 0;
}
背写程序时出现很多问题,是没有形成自己的代码风格,需要注意的地方:
1.定义隔离行、列数(即空行和空列)pad的意义在于能够用变量控制,修改变量值即可变形。
用const定义更好地说明它是人为定义的常量,增强代码可读性。
2.用到string的size方法的地方,定义了string::size_type类型的变量,保持一致。
3.双层循环的里层,没有用for语句,因为c的变化不整齐,这样写更好看。