1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// declare functions
// void function to open the input and output files
void openFiles (ifstream& input, ofstream& output);
// void function to read the names in the file
void readNames (ifstream& input, string& fullname);
// void function to change the name format
void changeNames (ifstream& input, string fullname, string firstname,
string middlename, string lastname);
// void function to output the results to the output file
void printResults (string&, string&);
int main()
{
// declare variables within main
string fullname, firstname, middlename, lastname;
ifstream input;
ofstream output;
openFiles (input, output);
readNames (input, fullname);
changeNames (input, fullname, firstname, middlename, lastname);
system ("pause");
}
// make a function to open the input and ouput files
void openFiles (ifstream& input, ofstream& output)
{
input.open ("input.txt");
// check to see that the input file can be opened
if ( ! input )
{
// if it can't, give an error message
cout << "Input file could not be opened! ";
// and close the program
exit (1);
}
output.open("output.txt");
// check to see that the output file can be opened
if (! output)
{
// if it can't, give an error message
cout <<"The output file could not be opened! ";
// and close the program
exit (1);
}
}
// have a function read the names and get the name size
void readNames (ifstream& input, string& fullname)
{
while (getline(input, fullname));
}
void changeNames (ifstream& input, string fullname, string firstname,
string middlename, string lastname)
{
int comma = fullname.find(',');
int length = fullname.length();
lastname = fullname.substr (0, comma);
int space = fullname.find(' ', comma +2);
do
{
input>>fullname;
if (space!= -1)
{
firstname = fullname.substr(comma + 2, space - comma -2);
middlename = fullname.substr(space + 1, length);
cout<< firstname <<", "<<middlename <<", ";
}
else
{
firstname = fullname.substr(comma + 2, length);
cout<< firstname <<", ";
}
cout<<lastname<<endl;
}
while (input);
}
|