summaryrefslogtreecommitdiff
path: root/CPP/cpp_book/chap2/greeting.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'CPP/cpp_book/chap2/greeting.cpp')
-rw-r--r--CPP/cpp_book/chap2/greeting.cpp54
1 files changed, 54 insertions, 0 deletions
diff --git a/CPP/cpp_book/chap2/greeting.cpp b/CPP/cpp_book/chap2/greeting.cpp
new file mode 100644
index 0000000..516d36a
--- /dev/null
+++ b/CPP/cpp_book/chap2/greeting.cpp
@@ -0,0 +1,54 @@
+#include <iostream>
+#include <string>
+
+#define ROW_PAD 5
+#define COL_PAD 8
+
+int main(void)
+{
+ using std::cout; using std::endl;
+ using std::cin; using std::string;
+
+ const int rows = ROW_PAD * 2 + 3; // empty + first/last line + greeting
+ string name;
+
+ cout << "Enter your name: ";
+ cin >> name;
+
+ const string greeting = "Hello " + name + "!";
+ const string::size_type cols = COL_PAD * 2 + greeting.size() + 2;
+
+ cout << endl;
+
+ /*
+ * Loop invariant:
+ * -We've written 'r' rows so far
+ */
+ const string col_blank(COL_PAD, ' ');
+ const string row_blank(cols - 2, ' ');
+ for (int r = 0; r != rows; r++) {
+
+ string::size_type c = 0;
+ /*
+ * Loop invariant:
+ * - We've written 'c' columns so far
+ */
+ while (c != cols) {
+ if (r == ROW_PAD + 1 && c == 1) {
+ cout << col_blank << greeting << col_blank;
+ c += greeting.size() + (col_blank.size() * 2);
+ } else {
+ if (r == 0 || r == rows - 1 ||
+ c == 0 || c == cols - 1) {
+ cout << "*";
+ c++;
+ } else {
+ cout << row_blank;
+ c += row_blank.size();
+ }
+ }
+ }
+ cout << endl;
+ }
+ return 0;
+}