Accelerated C++学习笔记 Ch2

/* ----------------------------------------------------- *
	Ch2 循环与计数
	说明:引用书中代码,略有改动
 * ----------------------------------------------------- */

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter your name:";
    string name;
    cin >> name;
    cout<<endl;

	const string greeting = "Hello,"+name+"!" ;
	const int pad = 2;//1
	const int rows = 3 + 2 * pad;
	const string::size_type cols = 2 + greeting.size() + pad * 2; // 注意类型

	string::size_type c=0; // 把定义放在了循环外
	for(int r=0;r!=rows;r++) // 1 用r!=rows而不用r<rows固定结束条件 2 在for循环中定义
	{
	    c=0;// 一行开始注意清零,写循环时注意下次执行循环是否仍正确
		while(c!=cols)
		{
			if(r==pad+1&&c==pad+1)
			{
				cout<<greeting;
				c+=greeting.size()-1;// 注意保持数据的含义,这里书中有点小毛病,减去1就行了
			}
			else
			{
                if(r==0||r==rows-1 ||
                    c==0||c==cols-1)
                    cout<<"*";
                else
                    cout<<" ";
			}
			c++;
		}
		cout<<endl;
	}
	cout<<"end"<<endl;
    return 0;
}
/* ----------------------------------------------------- *
Please enter your name:Tom

****************
*              *
*              *
*  Hello,Tom!  *
*              *
*              *
****************
end

Process returned 0 (0x0)   execution time : 4.970 s
Press any key to continue.
 * ----------------------------------------------------- */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值