输出如下字符图形:
****************
* *
* Hello, Eddy! *
* *
****************
源代码:
#include <iostream>
#include <string>
using namespace std;int main()
{
//ask for the person's name
cout<<"Please input your first name: ";
//read the name
string name;
cin>>name;//build the message that we intend to write
const string greeting = "Hello, " + name + "!";//the number of blanks surrounding the greeting
const int pad = 5;
//the number of rows and columns to write
const int rows = pad * 2 +3;
const string::size_type cols = greeting.size() + pad * 2 +2;
//write a blank line to separate the output from the input
cout<<endl;//write rows rows of output
//invariant:we have written r rows so far
for (int r = 0; r != rows; ++r)
{
string::size_type c = 0;//invariant:we have written c characters so for in then couurent row
while (c != cols)
{
//is it time to write greeting?
if (r == pad + 1 && c == pad + 1)
{
cout<<greeting;
c += greeting.size();
}
else
{
//are we on the border?
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1)
{
cout<<"*";
c++;
}
else
{
cout<<" ";
c++;
}
}
}
cout<<endl;
}
return 0;
}
算数操作符较关系操作符优先级要高;
短路求值法
循环不变式的概念:循环开始及每次结束都为真;
size_type来自String类,无符号类型,表示一个String中含有字符的数目
已经有(0)位网友发表了评论,你也评一评吧!
原创文章如转载,请注明:转载自Eddy Blog
原文地址:http://www.rrgod.com/program/303.html 欢迎订阅Eddy Blog。
Tags:Accelerated C