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 Version | string 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;
} |