C++ First Last Name

Write a program that reads in the first and last name of a person and formats the full name as the last name, followed by a comma, a space, and the first name. For example:

Please enter your first and last name on the next line.
Harry Morgan
Morgan, Harry
#include <iostream>
#include <string>

using namespace std;

int main()
   cout << "Please enter your first and last name on the next line." << endl;
   string name;
   getline(cin, name);
   size_t pos = name.find(" ");
   string last_name = name.substr(pos);
   string first_name = name.substr(0, pos);
   string full_name = last_name + ", " + first_name;
   cout << full_name.substr(1) << endl;
   return 0;

Write a sequence of input statements to read a user’s first, middle, and last name and then print a monogram. For instance, if the user enters Franklin Delano Roosevelt, then the program prints FDR.

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

int main()
   cout << "Enter your first, middle, and last name: ";
   string first;
   string middle;
   string last;
   cin >> first >> middle >> last;
   cout << first.front() <<  middle.front() << last.front();
   return 0;

Write the function processName(). It’s input is a full name in the form (First MI. Last). Your job is to use string member functions to break the name into the first name, last name and middle initial, and return the processed name in the form “Last, First MI.”.

Use the string member functions substr()find()rfind()find_first_not_of()find_last_not_of() and at() to solve this problem.

You may assume:

  • that every name will have exactly one word for the first and last names and a single character, followed by a period for the middle initial.
  • There will be at least one space separating each of the portions of the input name, but there may be more spaces.
#include <string>
using namespace std;

    Processes a name containing First MI. Last.
    @param s the name formatted as described.
    @return the name processed to "Last, First MI."
    Include the quotes in the returned name.
string processName(const string& s)
   string result;
   size_t pos1 = s.find_first_not_of(' ');
   size_t pos2 = s.find_last_not_of(' ');
   string clean = s.substr(pos1, pos2 - pos1 + 1);
   size_t pos3 = clean.find(' ');
   string first = clean.substr(0, pos3);
   string last = clean.substr(clean.rfind(' ') + 1);
   string middle = clean.substr(clean.find(' '), clean.rfind(' ') - clean.find(' '));
   middle = middle.substr(middle.find_first_not_of(' '), middle.find_last_not_of(' ') - middle.find_first_not_of(' ') + 1);
   result = last + ", " + first + " ";
   result += middle;
   return result;