I am required to read in records from a file and store them in descending
order by an customer number, which is a c-style string of length 5. I am
storing these records in a linked list. My problem is in comparing the
customer number I just read in with those in the list. I'm not sure how to
go about comparing c-style strings for greater than, less than.. here is how
I am currently trying to do it:
while( ( custinfo.number > (*itr).number ) && itr != L.end() )
I want to compare the c-style strings, and if the one read in is greater
than the one the iterator is pointing to, then increment the iterator. When
I run the program as it is shown below, the output produced is equal to the
input file, so there is NO sorting going on. Can anyone help me fix this,
or offer a better way of sorting in descending order by customer number?
The code I have so far is shown below:
#include <iomanip>
#include <iostream>
#include <fstream>
#include <list>
using namespace std;
struct info
{
char number[6]; // Customer number
char name[21]; // Customer name
float balance; // Customer balance
};
class records
{
private:
ifstream infile; // input file stream for processing
info custinfo; // holds customer info being read in
public:
records( list<info>&, list<info>::iterator );
~records();
};
records::records( list<info> &L, list<info>::iterator itr )
{
// open the file for input
infile.open( "customer.dat" );
// check to see if the file is opened
if( infile.fail() )
{
// print an error message and exit the program
cout << "Error opening customer.dat" << endl;
exit(1);
}
// the file is now open for input; gather the existing
// customer records and store them in the list
itr = L.begin();
do
{
// read in a record to the struct
infile.read( (char *) &custinfo, sizeof(custinfo) );
// add the first record
if( L.empty() )
L.push_back( custinfo );
else
{
// add the record in sequential order by customer number
itr = L.begin();
while( itr != L.end() ) //( custinfo.number > (*itr).number ) &&
itr != L.end() )
{
if( custinfo.number > (*itr).number )
{
cout << custinfo.number << " > " << (*itr).number << endl;
itr++;
}
}
// insert the record
L.insert( itr, custinfo );
}
itr = L.begin();
} while( !infile.eof() );
}
records::~records()
{
infile.close();
}
int main()
{
list<info> L;
list<info>::iterator itr;
records customer( L, itr );
// remove this
for( itr = L.begin(); itr != L.end(); itr++ )
{
cout << setw(30) << itr->number << setw(20) << itr->name <<
itr->balance << endl;
}
return 0;
}