I'm having trouble with a program. The program needs to do a selection sort of last names. I have the program sorting the names correctly, but I can not get the correct first name to appear next to its last name. I've tried a loop and either get the same name or an incorrect name. The code and data follows.
#include <fstream>
#include <string>
#include <iomanip>
#include <iostream>
using namespace std;
void sortData(string lName[], int noOfRows);
int main ()
{
// step 1
string lName[15];
string fName;
int age, wTime, i = 0, j, k, num = 0;
char sex;
ifstream inFile; // input stream variable for data file
ofstream outFile; // output stream variable for result data
inFile.open("data.txt");
if (!inFile) // step 3
{
cout << "Cannot open the input file." << endl;
return 1;
}
outFile.open("results.txt");// step 4
while (!inFile.eof())
{
inFile >> fName >> lName[i++] >> age >> sex >> wTime;
}
sortData(lName, i);
for (k = 0; k < i; k++)
{
outFile << lName[k] << " " << endl;
outFile << fName << endl;
}
return 0;
}
void sortData(string lName[], int noOfRows)
{
int i, j;
int min;
// selection sort
for (i = 0; i < noOfRows - 1; i++)
{
// step a
min = i;
for (j = i + 1; j < noOfRows; j++)
if (lName[j] < lName[min])
min = j;
if(min!=i)// step b
lName[i].swap(lName[min]);
}
}
Michael Brooks 13 M 33
Amy Shields 30 F 40
Clara Miles 50 F 30
Robert Davidson 20 M 45
Joshua Chase 25 M 42
Jackie Choker 20 F 29
Sarla Kothari 60 F 37
George Runner 53 M 49
Sally Jones 19 F 47