如何用更为生动的语言来问候,就像下面的输入输出一样:
Please enter your first name: Bob ************** * * * Hello,Bob! * * * **************我们的程序会产生五行输出。
第一行是框架的开始。它是一个*字符组成的序列,它的长度是人的名字、问候语("Hello,")、两端的空格和*所占的字符的总长。
第二行由相应数目的空格和两端的*组成。
第三行的结构是一个*、一个空格、问候语、一个空格和一个*。
最后两行分别与第二行和第一行相同。
为了完成这样的输出,明智的实现策略是每次一行的进行输出。
首先读取名字,然后使用名字来组成问候语,接下来使用问候语来建立每行的输出。
下面的程序就采用了这种策略来解决这个问题:
#include<iostream> #include<string> using namespace std; int main() { //ask for person's name cout << "Please enter your first name:"; //read the name string name; cin >> name; //build the message that we intend to write const string greeting = "Helllo," + name + "!"; //the number of blanks surrounding the greeting const int pad = 1; //total number of rows to write const int rows = pad * 2 + 3; //seprate the output from the input cout << endl; //write rows rows of output int r = 0; //invariant:we have written r rows so far while (r != rows) { //write a row of output cout << endl; ++r; } //we can conclude that the invariant is true here const string::size_type cols = greeting.size() + pad * 2 + 2; //write a black line to separate the output from input cout << endl; //write rows rows of input //invariant:we have written r rows so far for (r = 0; r != rows; ++r) { string::size_type c = 0; //invariant:we have written c characters so far in the current row 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; } system("pause"); return 0; }const(常量)可以作为变量定义的一部分。这么做可以保证,在变量的生存期内,不会改变它的值。
在一个程序中,指出哪些变量不会改变,可以让程序更容易理解。
如果说一个变量是常量(const),必须在定义的时候初始化,否则就再也没有机会给它赋值了。
用来初始化const变量的值,可以不是常数(constant)。
通过使用圆括号,可以要求系统根据表达式来构造(construct)变量。
greeting.size()是一个调用成员函数(member function)的例子。
事实上,名叫greeting的对象含有一个成员叫size,它是一个函数,我们可以通过调用它获得一个值。
' '是一个字符直接量(character literal),值为空格。
字符直接量总是被单引号括住;而字符串直接量总是被双引号括住。
字符直接量的类型是内置于语言核心的char类型。
如果我们想要得到字符 ' 或者 \ ,我们必须在前面加上 \ 。