/*--- Examples for Week 9 Lecture 2 Designing more C++ (non-main) functions using the design recipe, involving string operator + and string method length. (Also some additional "playing around" in the main function) compile using: g++ 111lect09-2.cpp -o 111lect09-2 run using: ./111lect09-2 by: Sharon Tuttle last modified: 2026-10-22 ---*/ #include <cstdlib> #include <iostream> #include <string> #include <cmath> using namespace std; /*=== signature: pretty_name: string string -> string purpose: expects a first name and last name, and returns the last name and first name separated by a comma and a blank in that order tests: pretty_name("John", "Doe") == "Doe, John" pretty_name("Joan", "of Arc") == "of Arc, Joan" ===*/ string pretty_name(string first_name, string last_name) { return last_name + ", " + first_name; } /*=== signature: name_length: string string -> int purpose: expects a first and last name, and returns the number of characters in both combined tests: name_length("Jane", "Doe") == 7 name_length("Napoleon", "Dynamite") == 16 ===*/ int name_length(string first_name, string last_name) { return first_name.length() + last_name.length(); } /*--- test the functions above, and also try out a few things related to the string + operator and the string length method ---*/ int main() { cout << boolalpha; cout << endl; cout << "*** Testing: pretty_name ***" << endl; // put each of your function's tests into a cout statement // to print its result cout << (pretty_name("John", "Doe") == "Doe, John") << endl; cout << (pretty_name("Joan", "of Arc") == "of Arc, Joan") << endl; // just for fun: cout << pretty_name("Joan", "of Arc") << endl; // string method call demo! const string FIRST_COURSE = "CS 111"; cout << endl; cout << "length of " << FIRST_COURSE << ": "; cout << FIRST_COURSE.length() << endl; cout << endl; cout << "*** Testing: name_length ***" << endl; cout << (name_length("Jane", "Doe") == 7) << endl; cout << (name_length("Napoleon", "Dynamite") == 16) << endl; // ADDED AFTER CLASS - more playing with string class + operator, // for appending string instances /*--- Operator + has been defined for the string type/string class; it can be used to append string instances, returning a new string instance It ONLY WORKS if at least ONE of its operands is of type string! ...but as long as at least one operand is of type string, you can use it to append a string to a char* OR a string to a char...! (compiler converts them to string) ---*/ cout << endl; cout << "More playing with string + operator:" << endl; const string FIRST = "Charlie"; const string LAST = "Brown"; cout << (FIRST + LAST) << endl; // CharlieBrown cout << (FIRST + " " + LAST) << endl; // Charlie Brown cout << (FIRST + '-' + LAST) << endl; // Charlie-Brown // UNCOMMENT this to see that + is NOT defined for // type char*: //cout << ("m" + "oo") << endl; // fails, both are char* cout << endl; return EXIT_SUCCESS; }