With some minor adjustments, we can use the C++ string class to accomplish our goal. We will use the C++ member function ‘append’ from the string class. My solution if fairly clean and simple. Here is the source:
4. Write a program that asks the user to enter his or her first name and then last name, and
that then constructs, stores, and displays a third string consisting of the user’s last name
174 C++ PRIMER PLUS, FIFTH EDITION
followed by a comma, a space, and first name. Use string objects and methods from the
string header file. A sample run could look like this:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: Fleming, Flip
#include <iostream> #include <string> using namespace std; int main() { string firstName; string lastName; string str; // Gather input, could use cin.getline here. cout << "Enter your first name: "; cin >> firstName; cin.ignore(); cout << "Enter your last name: "; cin >> lastName; // Using C++ string member functions str.append(lastName); str.append(" , "); str.append(firstName); cout << "Here's the information in a single string: " << str << endl; cin.get(); return 0; }