Do you know how to input a line of text and parse it?
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Why a char array for the middle name when you are already using strings? If you can use vectors and stringstreams, the normal C++ way, I'd do something like this.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
string line;
cout << "Enter your first name, middle name or initial and last name in that order\n";
if ( getline(cin, line) )
{
vector<string> name;
istringstream iss(line);
while ( iss >> line )
{
name.push_back(line);
}
if ( name.size() > 2 )
{
cout << name[2] << ", " << name[0] << ' ' << name[1][0] << ".\n";
}
else
{
cout << name[1] << ", " << name[0] << "\n";
}
}
return 0;
}
/* my output
Enter your first name, middle name or initial and last name in that order
John Quincy Public
Public, John Q.
*/
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
That works if the user enters three names. If they only enter two names you will have the last name as the middle name, though.
If you're not familiar with stringstreams as demonstrated by Dave Sinkula you can parse the entire line using other techniques such as strtok() or your own method.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396