Code:
//******************************************************************
// PrintName program
// This program prints a name in two different formats
//******************************************************************
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string FIRST; // Person's first name
string LAST; // Person's last name
char MIDDLE; // Person's middle initial
ifstream inPut; // Data File
ofstream outPut;
int main()
{
inPut.open("names.dat");
outPut.open ("output.dat");
if ( !inPut )
{
cout << "Can't open the input file.";
return 1;
}
inPut >> FIRST >> LAST >> MIDDLE;
while (inPut)
{
string firstLast; // Name in first-last format
string lastFirst; // Name in last-first format
firstLast = FIRST + " " + LAST;
outPut << "Name in first-last format is " << firstLast << endl;
lastFirst = LAST + ", " + FIRST + ", ";
outPut << "Name in last-first-initial format is ";
outPut << lastFirst << MIDDLE << '.' << endl;
inPut >> FIRST >> LAST >> MIDDLE;
}
inPut.close();
return 0;
}
Above is my program. The idea of it is to plug in names provided in a file, and have them outputted in Last-First, and Last-First-Middle Initial.
Problem: Two of the names in my file (provided by my teacher) have no middle initial, and so the program reads the first letter of the next name as the other person's middle initial. How do I rectify this program so that my program does not continue on to the next line of data? Below are my input values for names.
George Bush W
Madhavi Gandhi D
Dan Berk G
Ameka Johnson P
Rita Hayward C
Clint Eastwood B
Sara-Jessica Parker
Larry Kind L
Rani Mukharji
This is my current output:
Name in first-last format is George Bush
Name in last-first-initial format is Bush, George, W.
Name in first-last format is Madhavi Gandhi
Name in last-first-initial format is Gandhi, Madhavi, D.
Name in first-last format is Dan Berk
Name in last-first-initial format is Berk, Dan, G.
Name in first-last format is Ameka Johnson
Name in last-first-initial format is Johnson, Ameka, P.
Name in first-last format is Rita Hayward
Name in last-first-initial format is Hayward, Rita, C.
Name in first-last format is Clint Eastwood
Name in last-first-initial format is Eastwood, Clint, B.
Name in first-last format is Sara-Jessica Parker
Name in last-first-initial format is Parker, Sara-Jessica, L.
Name in first-last format is arry Kind
Name in last-first-initial format is Kind, arry, L.