this program reads in a First name, middle name or initial, last name and then outputs the last name, first name then middle initial. The problem is when you don’t give a middle name or initial then the program output Is not correct. Look below for the output. The output should just be User, Mary when middle initail or name is not given.
Please be specific as to where i need to make the adjustment.
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
int const MAX_NAME = 20 ;
using namespace std;
int main()
{
char fName [MAX_NAME + 1];
char mOrInitial [MAX_NAME + 1];
char lName [MAX_NAME + 1];
char temp1 [MAX_NAME + 1];
char temp2 [MAX_NAME + 1];
cout << "Enter first name, then middle name or initial, and then last name: " << endl ;
char szBuff [80] ;
cin.getline(szBuff, 80, '\n') ;
char* p = szBuff ; // get first name
char* p1 = fName ;
while ((*p1++ = *p++) != ' ' && *p != '\0') ;
*p1 = '\0' ;
while (*p == ' ' && *p != '\0') p++ ;
p1 = temp1 ;
while ((*p1++ = *p++) != ' ' && *p != '\0') ;
*p1 = '\0' ;
while (*p == ' ' && *p != '\0') p++ ;
if (*p)
{
p1 = temp2 ;
while ((*p1++ = *p++) != ' ' && *p != '\0') ;
*p1 = '\0' ;
}
if ('\0' == temp2 [0]) // no middle name was given
{
strcpy (lName, temp1) ;
}
else
{
strcpy (mOrInitial, temp1) ;
strcpy (lName, temp2) ;
}
// Last_Name, First_Name Middle_Initial.
if ('\0' == mOrInitial[0])
{
printf (lName) ; printf (", ") ;
printf (fName) ;
}
else
{
printf (lName) ; printf (", ") ;
printf (fName) ; printf (" ") ;
printf ("%c.", mOrInitial[0]) ;
}
printf ("\n") ;
_getch () ;
return 0;
}
//Right format with middle name given
//Enter first name, then middle name or initial, and then last name:
//Mary Average User
//User, Mary A.
//Press any key to continue . . .
//Not right without giving middle name. Output should be just User, Mary.
//Enter first name, then middle name or initial, and then last name:
//Mary User
//╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠User, Mary U.