/* ----------------------------------------------------- *
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.
* ----------------------------------------------------- */
Accelerated C++學習筆記 Ch2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.