Apr 19, 2011 at 3:28pm UTC
I am having to write a program that reads in two files (file1.txt and file2.txt) and sorts them into a master file (report.txt.). File1 is NOT sorted and file2 is already sorted. Below is my code from a previous project and I plan on re-using most of it, however I need to add a sort function/array above the WHILE loop. Please let me know if you can help. I am having trouble sorting file1 by it's name. Each file contains lines of data that look like this...
"Alex Letterhead Elegant 96 2 21126
Ana Letterhead Elegant 96 1 21121
Claudette Letterhead Excalibur 40.9 1 21125
Colin Note Impression 88.5 1 21126
Earl Note Inspire 74.9 1 21123
Fred Note Imagine 62.5 1 21122
Grace Letterhead Excelsior 68.5 1 21125
Henri Letterhead Excelsior 68.5 1 21122
Hermine Note Impression 88.5 1 21124"
that is Name, type, style, price, quantity, zipcode.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct transaction
{
string name;
string type;
string style;
double price;
double quantity;
string zip;
};
ostream& operator << (ostream& os, transaction rep)
{os << rep.name << "\t" << rep.type << "\t" << rep.style << "\t" << rep.price << "\t" << rep.quantity;
return os;}
void main()
{
char ch;
transaction rep[2];
ifstream indataFile1;
ifstream indataFile2;
ofstream outdataReport;
indataFile1.open("file1.txt");
indataFile2.open("file2.txt");
outdataReport.open("report.txt");
indataFile1 >> rep[0].name >> rep[0].type >> rep[0].style >> rep[0].price >> rep[0].quantity >> rep[0].zip;
indataFile2 >> rep[1].name >> rep[1].type >> rep[1].style >> rep[1].price >> rep[1].quantity >> rep[1].zip;
while(!indataFile1.eof() || !indataFile2.eof())
{
if (indataFile1.eof())
{
while (!indataFile2.eof())
{
outdataReport << rep[1] <<endl;
indataFile2 >> rep[1].name >> rep[1].type >> rep[1].style >> rep[1].price >> rep[1].quantity >> rep[1].zip;
}
}
else if (indataFile2.eof())
{
while (!indataFile1.eof())
{
outdataReport << rep[0] << endl;
indataFile1 >> rep[0].name >> rep[0].type >> rep[0].style >> rep[0].price >> rep[0].quantity >> rep[0].zip;
}
}
else
{
if (rep[0].name < rep[1].name)
{
outdataReport << rep[0] <<endl;
indataFile1 >> rep[0].name >> rep[0].type >> rep[0].style >> rep[0].price >> rep[0].quantity >> rep[0].zip;
}
else
{
outdataReport << rep[1] << endl;
indataFile2 >> rep[1].name >> rep[1].type >> rep[1].style >> rep[1].price >> rep[1].quantity >> rep[1].zip;
}
}
}
indataFile1.close();
indataFile2.close();
outdataReport.close();
cout << "Both files have been merged into a" <<endl;
cout << "single summary report, called report.txt" << endl <<endl;
cout << endl << endl << "Enter 0 to quit" << endl;
cin >> ch;
return;
}