I am attempting to write a program that reads names from a file, rearranges the names, and then writes them to a new file in a different order. In the original file there are the following names below:
Miller, Jason Brian
Blair, Lisa Maria
Gupta, Anil Kumar
Arora, Sumit Sahil
Saleh, Rhonda Beth
I created a second file removing the middle names to test my conditional statement. The problem I have is that in my attempt to make a conditional statement for if the individual has a middle name or not the results puts the initial of the last name "Miller" in place in the first result giving me Jason M Miller for example in the first line.
#include<iostream>
#include<string>
#include<fstream>
usingnamespace std;
int main()
{
ifstream infile;
ofstream outfile;
//starts lastName middleName firstName
//ends firstName middleName lastName
//opening the input file and creating output file
infile.open("Names.txt");
outfile.open("NamesRevised.txt");
string first, middle, last;
string names = " ";
int x = 0;
int y = 0;
int z = 0;
//Put any number of names in file
while (!names.empty())
{
getline(infile, names);
//I will find the last name below.
x = names.find(",");
last = names.substr(0,x);
/*Below I will erase the first space in the string to make my find function easier. I find the first name.*/
names.erase(x+1,1);
y = names.find(" ");
first = names.substr(x+1,y-x-1);
//Below I will find the middle name.
if (names == "\0")
{
z = names.length();
middle = names.substr(y+1,z-y);
}
//One for testing one for writing.
cout << first << " " << middle << " " << last << endl;
outfile << first << " " << middle << " " << last << endl;
}
system("pause");
return 0;
}