8.3.3. name_box.cpp, Version 3

Time: 00:02:23 | Download: Large Small | Streaming

The third and final version of the name_box program solves the same problem as the previous two: drawing a box around a user's name. Furthermore, the third version is structurally identical to name_box1.cpp. So similar are the two versions that the accompanying video begins with the first version and changes the variable name from a C-string to an instance of the C++ string class. The changes are few and straightforward:

#include <iostream>
#include <string>					// (a)
using namespace std;

int main()
{
	string	name;					// (b)

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

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

	cout << "|" << name << "|\n";			// (e)

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

	return 0;
}
name_box3.cpp. The example highlights in yellow the few changes necessary to convert name_box1.cpp to name_box3.cpp.
  1. The string class header file replaces the C-string header file: change <cstring> to <string>
  2. Change the data type defining name from character array (C-string) to the string class; name becomes an instance of the string class; i.e., a string object.
  3. The extractor operator, >>, fails to read past spaces with strings and C-strings alike. So, we again use a getline function, but despite having the same name, this is not the same function. Please compare the two getline functions carefully.
  4. We replace the C-string strlen function call to the string member function length (notice that we use the dot operator to call member functions.
  5. We don't need to make any changes to print the name; the inserter operator, <<, works with string objects without error.