8.3.3. name_box.cpp, Version 3

The third and final version of the name_box program solves the same problem as the previous versions: drawing a box around a name. The third version parallels the first, and the two are structurally the same. The following figure contrasts the two solutions.

C-String Versionstring Class Version
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char	name[100];

    cout << "Please enter your name: ";
    cin.getline(name, 100);

    cout << "+";
    for (size_t i = 0; i < strlen(name); i++)
        cout << "-";
    cout << "+" << endl;

    cout << "|" << name << "|" << endl;

    cout << "+";
    for (size_t i = 0; i < strlen(name); i++)
        cout << "-";
    cout << "+" << endl;

    return 0;
}

(a)




(b)


(c)


(d)






(d)





#include <iostream>
#include <string>
using namespace std;

int main()
{
    string	name;

    cout << "Please enter your name: ";
    getline(cin, name);

    cout << "+";
    for (size_t i = 0; i < name.length(); i++)
        cout << "-";
    cout << "+" << endl;

    cout << "|" << name << "|" << endl;

    cout << "+";
    for (size_t i = 0; i < name.length(); i++)
        cout << "-";
    cout << "+" << endl;

    return 0;
}
name_box3.cpp. The figure compares two solutions to the namebox problem, each using a different string implementation. It's instructive to compare how the different representations perform the equivalent operations (highlighted in the programs).
  1. C++ declares C-strings and the string class in <cstring> and <string>, respectively.
  2. Each version defines a variable, name, to store data read from the console.
  3. Although both programs read data from the console with a getline function, they are overloaded and not the same function. The function highlighted in blue is part of the I/O system and is declared in <iostream>, while the function highlighted in pink is declared in the <string> header file.
  4. Finding a string's length is a frequent task for both implementations. Notice that in the procedural or non-object-oriented version (blue) treats name as passive data - it's passed as an argument inside the parentheses and strlen operates on it. In contrast, the object-oriented version (pink) binds name to the length function with the dot operator - we think of the program "requesting" name to report its length.