I am trying to sort a record according to their respective number like this:

5 reyes d r 1 2 3
3 delos d k 4 5 6
9 go t r 7 4 5
1 po w w 2 2 2
2 bun b m 3 3 3

then it will become:

1 po w w 2 2 2
2 bun b m 3 3 3
3 delos d k 4 5 6
5 reyes d r 1 2 3
9 go t r 7 4 5

here is the definition of the code:

void sortRec()
{
	fstream data,temp;
	string line;
	int size(0);
	int id[500];

	data.open("employee.txt",ios_base::in);

	//counting lines
	data.seekg(0,ios::beg);
	while(getline(data,line))
			{size++;}

	data.clear();
	data.seekg(0,ios::beg);
	for(int i=0;i<size;i++)
	{
		data>>id[i]>>e.name.lname>>e.name.fname>>e.name.mname>>e.address>>e.hour>>e.hRate;
	}
	//sorting employee numbers
	for(int a=0;a<size;a++)
	{
		for(int b=a+1;b<size;b++)
		{
			if(id[b]<id[a])
			{
				int tmp;
				tmp=id[a];
				id[a]=id[b];
				id[b]=tmp;
			}
		}
	}

	data.close();

	//sorting the data
	rename("employee.txt","tempfile.txt");

	data.open("employee.txt",ios_base::app);
	temp.open("tempfile.txt",ios_base::in);

	int _id;
	for(int i=0;i<size;i++)
		{
			temp>>_id;
			temp>>e.name.lname>>e.name.fname>>e.name.mname>>e.address>>e.hour>>e.hRate;
			for(int a=0;a<size;a++)
				{
					if(id[a]==_id)
					{data<<_id<<" "<<e.name.lname<<" "<<e.name.fname<<" "<<e.name.mname<<" "<<e.address<<" "<<e.hour<<" "<<e.hRate<<'\n';}

			}
	}

	data.close();
    temp.close();
	
    remove("tempfile.txt");
}

what i did is i get the E numbers of every record first then i sort them. then i open the file again and get the E numbers to compare to the sorted one then write it to the file.

but what happen is, it didn't sort, the files on the record remains the same :

5 reyes d r 1 2 3
3 delos d k 4 5 6
9 go t r 7 4 5
1 po w w 2 2 2
2 bun b m 3 3 3

Do anyone knows where in my code go wrong?

Member Avatar for jmichae3
#incloude <vector>
#include <iterator>
#include <stringstream>
using namespace std;


inline void swap(int& a, int& b) {	//I think swap is already defined as a macro somewhere in the STL...
	int tmp=a; 
	a=b; 
	b=tmp; 
}

//just make sure you are working with a copy of your emplyee data file.  
//either way, it's a good policy.
//this version reads, sorts, and writes. 
//not sure why you are making this so complicated for something that does the same thing.
//implement e as an array or vector.
//why aren't you using .sort() ?


void sortRec() {
	stringstream ss;
    fstream data,temp;
    char[5000+1] line;
	string sLine;
    int size=0;
    vector<int> id;
	vector<int>::iterator vi;
	int i=0;
     
    data.open("employee.txt",ios_base::in|ios_base::out);
     
    //counting lines
    data.seekg(0,ios::beg);
    while(data.good()) {
		data.getline(line,5000);
		sLine=line;
		ss.str(sLine);
		ss>>e[i].id
		  >>e[i].name.lname
		  >>e[i].name.fname
		  >>e[i].name.mname
		  >>e[i].address
		  >>e[i].hour
		  >>e[i].hRate;
		i++;
		size++;
	}
	
	//it doesn't matter if you sort the employee numbers if they are disconnected from the record!  
	//then you just get a bunch of sorted record id's and the 
	//why don't you make id a member of e?
	
    //sorting employees by employee number
    for(int a=0;a<size;a++) {
		for(int b=a+1;b<size;b++) {
			if(e.id[b]<e.id[a]) {
				swap(e[a], e[b]);
			}
		}
    }
	
	data.seekg(0,ios::beg)
	
	for(i = 0; i < size; i++) {
		data<<e[i].id<<" "
			<<e[i].name.lname<<" "
			<<e[i].name.fname<<" "
			<<e[i].name.mname<<" "
			<<e[i].address<<" "
			<<e[i].hour<<" "
			<<e[i].hRate<<'\n';
	}
    data.close();
}

thanks :) ... the truth is I just start programming a few months ago that's why i'm not yet familiar with that <vector> header file and .sort() and swap...... what i only know is the long basic methods.. xD ........
But thanks a lot..... i'll gonna study the corrections you had given, this is a big help for me :)


-Dianne-

Member Avatar for jmichae3

with .sort(), if it's not an integer you must define your own compare function and then declare it when you call sort.

http://www.cplusplus.com/reference/stl/vector/
I was thinking vector but it turns out vector does not have sort, which is really what you were trying to do (I thought maybe you had to do it the hard way - there are faster sorts like quicksort than bubble sort). so I would go with http://www.cplusplus.com/reference/stl/list/

all you would need to do is .push_back() your data object to get it in, and
you would need to create a class for the data (you can still access it like a structure if you wish, but it's generally discouraged).

doing something like this really well in C++ can get somewhat involved with friend functions for fstream shift-in and shift-out operators << and >>, the class for the data structure, and the STL stuff. I have not been able to get a plain data structure to work with collections. I have not tried a structure that has methods like a constructor and destructor (a simple test).

another method would be to perform a merge sort. the merge sort used to be used on mag-tape systems to sort records, so it is ideal for file-based sorting. but it is not the best in the world. this would allow you to prevent the C++ code bloat I am describing here

one of my questions was, just how many records are you going to be processing with this program? is this a serious database (you should be using an SQL RDBMS like postgresql and using it embedded with C++), or something that will fit into RAM on an average old 32-bit XP box with 256MB RAM?

many of the collections also have .swap() but it only swaps whole vectors, this swap's not what you want.

I am working on a .sort() version, that will be the next code I put in.

This is just my project in my programming class, it's not actually a serious database, it's just being run in the cmd black screen.... and the number of records that will be putted was just for testing purposes only maybe a 10 records will do (maximum of 500)...
thanks for the info's :)

-Dianne-

Member Avatar for jmichae3

here it is with unit testing.

01
903 Palooka Harva Joe 123 blooky lane, Blastoff, PA, 12345 40 9.5
id lname fname mname address hours hRate
12 Smodz_III Bletchley Fervin 123_Blooky_Ln,_Blast,_PA_98554 80 40.0
12 Smodz III Bletchley Fervin 123 Blooky Ln, Blast, PA 98554 80 40
-----start-----
5 reyes d r 1 2 3
3 delos d k 4 5 6
9 go t r 7 4 5
1 po w w 2 2 2
2 bun b m 3 3 3
2 bun b m 3 3 3
-----end-----
-----start-----
1 po w w 2 2 2
2 bun b m 3 3 3
2 bun b m 3 3 3
3 delos d k 4 5 6
5 reyes d r 1 2 3
9 go t r 7 4 5
9 go t r 7 4 5
-----end-----

the underscores are automatically converted to spaces to strings that normally have spaces can be coded with underscores so that cin or fstream string input won't mangle it into multiple different variables (putting double quotes around it doesn't work).

#define TEST

#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <iterator>
#include <sstream> //sorry, I thought it weas stringstream, but it's sstream, I am new to this really cool header
//stringstream turns string into a stream like iostream or like cin and cout or fstream.
//this lets you do REALLY COOL stuff.
using namespace std;
void stripunderscores(string& s);

class CEmployee {
	public:
        //can't initialize cars when you declare them in a class.  it's similar to a struct.
		int    id;
		string lname,
		       fname,
		       mname,
		       address;
		int    hours; //assume 24-hour hour, not 12-hour time format. did you mean hoursWorked?
		double hRate; //when the next version of cC++ comes out past C++11, then we will have boost,
		//which has a decimal data type.  this would be preferable, since float and double have
		//floating point errors repeatedly adding some numbers like .01

		//2 different constructors
		CEmployee() {
			id     =0;
			lname  ="";
			fname  ="";
			mname  ="";
			address="";
			hours  =0;
			hRate  =0;
		}
		CEmployee(
			int _id,
			string& _lname,
			string& _fname,
			string& _mname,
			string& _address,
			int _hours,
			double _hRate
		) {
			id     =_id;
            lname  =_lname;
            fname  =_fname;
            mname  =_mname;
			address=_address;
			hours  =_hours;
			hRate  =_hRate;
		}
		CEmployee(
			int _id,
			string _lname,
			string _fname,
			string _mname,
			string _address,
			int    _hours,
			double _hRate
		) {
			id     =_id;
            lname  =_lname;
            fname  =_fname;
            mname  =_mname;
			address=_address;
			hours  =_hours;
			hRate  =_hRate;
		}
		//destructor that doesn't do anything
		~CEmployee() {}

		//property setting/getting functions
		void setid(int _id) {id=_id;}
		int getid() {return id;}

		void setlname(string _lname) {lname=_lname;}
		string getlname() {return lname;}

		void setfname(string _fname) {fname=_fname;}
		string getfname() {return fname;}

		void setmname(string _mname) {mname=_mname;}
		string getmname() {return mname;}

		void setaddress(string _address) {address=_address;}
		string getaddress() {return address;}

		void sethours(int _hours) {hours=_hours;}
		int gethours() {return hours;}

		void sethRate(double _hRate) {hRate=_hRate;}
		double gethRate() {return hRate;}

		//shift-in and shift-out I/O operators. must define as friends and not direct members.
		friend istream& operator>>(istream& is, class CEmployee& ce) {
			char line[65000+1];
			is.getline(line, 65000);
			line[64999]='\0';
			stringstream ss;
			string sLine=line, lname, fname, mname, address;
			int id, hours;
			double hRate;
			ss.str(sLine); //convert line to stringstream
			//input the record
            if (is.good() && ss.good()) {
                ss >> id
                   >> lname
                   >> fname
                   >> mname
                   >> address
                   >> hours
                   >> hRate;
                if (!ss.bad()) {
                    stripunderscores(lname);
                    stripunderscores(fname);
                    stripunderscores(mname);
                    stripunderscores(address);

                    //set the object's values using the interface provided
                    ce.setid(id);
                    ce.setlname(lname);
                    ce.setfname(fname);
                    ce.setmname(mname);
                    ce.setaddress(address);
                    ce.sethours(hours);
                    ce.sethRate(hRate);
                } else {
                    is.clear(ios_base::badbit|ios_base::failbit);
                }
            } else {
                is.clear(ios_base::badbit|ios_base::failbit);
            }
            return is;
		}
		friend ostream& operator<<(ostream& out, class CEmployee& ce) {
			out << ce.getid()      << " "
			    << ce.getlname()   << " "
			    << ce.getfname()   << " "
			    << ce.getmname()   << " "
			    << ce.getaddress() << " "
			    << ce.gethours()   << " "
			    << ce.gethRate()   << endl;
			return out;
		}
};


//this function strips _ out of strings.
//this allows strings that would normally have spaces in them to be coded with
//underscroes instead so that stringstream does not
void stripunderscores(string& s) {
    string s2;
    unsigned i;
    for (i=0; i < s.length(); i++) {
        if ('_'==s[i]) {
            s2 += ' '; //replace _ with a space
        } else {
            s2 += s[i]; //append the current character
        }
    }
    s=s2; //assign string back to original
}





//sorting comparison function for .sort()
//you can make this a more complicated comparison function if you want to sort by
//employee name and then by id instead.
bool sortcomparebyid(CEmployee first, CEmployee second) {
	/*
	//sort by employee lname,fname,mname and then by id
	if (first.getlname() < second.getlname()) {
		return true;
	} else {
        if (first.getfname() < second.getfname()) {
            return true;
        } else {
            if (first.getmname() < second.getmname()) {
                return true;
            } else {
                if (first.getid() < second.getid()) {
                    return true;
                } else {
                    return false;
                }
            }
        }
	}
	*/
	//sort by simple id comparison
	return first.getid() < second.getid();
}


//just make sure you are working with a copy of your emplyee data file.
//either way, it's a good policy.
//this version reads, sorts, and writes.
//not sure why you are making this so complicated for something that does the same thing.
//implement e as an array or vector.
//why aren't you using .sort() ?

void sortRec(char * filepath) {
    fstream flatDatabaseFile(filepath, ios_base::in|ios_base::out);
    list<class CEmployee> employees; //let's be realistic, these is a collection of employees
	list<class CEmployee>::iterator li;
	CEmployee employeeRecord; //temporary record variable for reading data into collection

    //counting lines
    while(flatDatabaseFile.good()) {
		flatDatabaseFile >> employeeRecord;
		employees.push_back(employeeRecord);
	}




	//it doesn't matter if you sort the employee numbers if they are disconnected from the record!
	//then you just get a bunch of sorted record id's and the
	//why don't you make id a member of e?

	employees.sort(sortcomparebyid); //feed it the compare function we wrote
	//rewrite the whole flat-file database
    flatDatabaseFile.clear();
    flatDatabaseFile.seekg(0, ios::beg); //reset get file pointer to start of file
    flatDatabaseFile.seekp(0, ios::beg); //reset put file pointer to start of file
    flatDatabaseFile.clear();
	for(li = employees.begin(); li != employees.end(); li++) {
		flatDatabaseFile << *li; //output the CEmployee object pointed to by the iterator li
	}
    flatDatabaseFile.close();
}

void show(char * filepath) {
    fstream flatDatabaseFile(filepath, ios_base::in);
	CEmployee employeeRecord; //temporary record variable for reading data into collection

    //counting lines
    flatDatabaseFile.seekg(0, ios::beg); //reset get file pointer to start of file
	cout<<"-----start-----"<<endl;
    while(flatDatabaseFile.good()) {
		flatDatabaseFile >> employeeRecord;
		cout<<employeeRecord;
	}
	cout<<"-----end-----"<<endl;
    flatDatabaseFile.close();
}

#if defined(TEST)
int main(void) {
    //test sortcomparebyid
    CEmployee c(
			903,
			string("Palooka"),
			string("Harva"),
			string("Joe"),
			string("123 blooky lane, Blastoff, PA, 12345"),
			40,
			9.50
		);
    CEmployee d(
			23,
			string("Palooka"),
			string("Harva"),
			string("Joe"),
			string("123 blooky lane, Blastoff, PA, 12345"),
			40,
			9.50
		);
    cout<<sortcomparebyid(c,d);
    cout<<sortcomparebyid(d,c)<<endl;

    //test the CEmployee
    cout<<c;
    cout<<"id lname fname mname address hours hRate"<<endl;
    cin>>c;
    cout<<c;


    //test sortRec
    char flatDatabaseFilepath[]="employee.txt";

	show(flatDatabaseFilepath);
	sortRec(flatDatabaseFilepath);
	show(flatDatabaseFilepath);



	return 0;
}
#endif
Member Avatar for jmichae3

I just realized that there needs to be a corresponding _ conversion function that does the reverse of the other one for the shift-out operator <<

sorry I wasn't thinking completely... if you did have data with the equivalent of spaces, not having this would corrupt your database every time you used sortRec().

//this function converts spaces to _ in strings.
//this allows strings that would normally have spaces in them to be coded with
//underscores instead so that stringstream does not 
//interpret the space as an argument separator like it normally does 
//(it needs to be a string made of non-whitespace characters).
string spacesto_(string s) {
    unsigned i;
    for (i=0; i < s.length(); i++) {
        if (' '==s[i]) {
             s[i]='_'; //replace _ with a space
        }
    }
    return s;
}
Member Avatar for jmichae3

I improved the code and expanded the database and fixed some stuff.
this will be the last post unless you wish me to respond.

//#define TEST

#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <iterator>
#include <sstream> //sorry, I thought it weas stringstream, but it's sstream, I am new to this really cool header
//stringstream turns string into a stream like iostream or like cin and cout or fstream.
//this lets you do REALLY COOL stuff.
using namespace std;
void _tospaces(string& s);
string spacesto_(string s);

class CEmployee {
    public:
        //can't initialize cars when you declare them in a class.  it's similar to a struct.
        int    id           ;
        string lastName     ,
               firstName    ,
               middleName   ,
               address1     ,
               address2     ,
               city         ,
               stateProvince,
               postalCode   ,
               country      ,
               department   ,
               mailstop     ,
               location     ;
        int    hours        ; //assume 24-hour hour, not 12-hour time format. did you mean hoursWorked?
        double hourlyRate   ; //when the next version of cC++ comes out past C++11, then we will have boost,
        //which has a decimal data type.  this would be preferable, since float and double have
        //floating point errors repeatedly adding some numbers like .01
        bool isBad;


        //2 different constructors
        CEmployee() {
            id              =0;
            lastName        ="";
            firstName       ="";
            middleName      ="";
            address1        ="";
            address2        ="";
            city            ="";
            stateProvince   ="";
            postalCode      ="";
            country         ="";
            department      ="";
            mailstop        ="";
            location        ="";
            hours           =0;
            hourlyRate      =0;
            isBad=true;
        }
        CEmployee(
            int    _id           ,
            string _lastName     ,
            string _firstName    ,
            string _middleName   ,
            string _address1     ,
            string _address2     ,
            string _city         ,
            string _stateProvince,
            string _postalCode   ,
            string _country      ,
            string _department   ,
            string _mailstop     ,
            string _location     ,
            int    _hours        ,
            double _hourlyRate
        ) {
            id              =_id             ;
            lastName        =_lastName       ;
            firstName       =_firstName      ;
            middleName      =_middleName     ;
            address1        =_address1       ;
            address2        =_address2       ;
            city            =_city           ;
            stateProvince   =_stateProvince  ;
            postalCode      =_postalCode     ;
            country         =_country        ;
            department      =_department     ;
            mailstop        =_mailstop       ;
            location        =_location       ;
            hours           =_hours          ;
            hourlyRate      =_hourlyRate     ;
            isBad=false;
        }
        //destructor that doesn't do anything
        ~CEmployee() {}

        void initialize() {
            id              =0;
            lastName        ="";
            firstName       ="";
            middleName      ="";
            address1        ="";
            address2        ="";
            city            ="";
            stateProvince   ="";
            postalCode      ="";
            country         ="";
            department      ="";
            mailstop        ="";
            location        ="";
            hours           =0;
            hourlyRate      =0;
            isBad           =true;
        }


        bool bad() {return isBad;}
        void setBad() {isBad = true;}
        void clearBad() {isBad = false;}
        void setBad(bool _isBad) {isBad = _isBad;}

        //property setting/getting functions
        void setid(int _id) {id=_id;isBad=false;}
        int getid() {return id;}

        void setlastName(string _lastName) {lastName=_lastName;isBad=false;}
        string getlastName() {return lastName;}

        void setfirstName(string _firstName) {firstName=_firstName;isBad=false;}
        string getfirstName() {return firstName;}

        void setmiddleName(string _middleName) {middleName=_middleName;isBad=false;}
        string getmiddleName() {return middleName;}

        void setaddress1(string _address1) {address1=_address1;isBad=false;}
        string getaddress1() {return address1;}

        void setaddress2(string _address2) {address2=_address2;isBad=false;}
        string getaddress2() {return address2;}

        void setcity(string _city) {city=_city;isBad=false;}
        string getcity() {return city;}

        void setstateProvince(string _stateProvince) {stateProvince=_stateProvince;isBad=false;}
        string getstateProvince() {return stateProvince;}

        void setpostalCode(string _postalCode) {postalCode=_postalCode;isBad=false;}
        string getpostalCode() {return postalCode;}

        void setcountry(string _country) {country=_country;isBad=false;}
        string getcountry() {return country;}

        void setdepartment(string _department) {department=_department;isBad=false;}
        string getdepartment() {return department;}

        void setmailstop(string _mailstop) {mailstop=_mailstop;isBad=false;}
        string getmailstop() {return mailstop;}

        void setlocation(string _location) {location=_location;isBad=false;}
        string getlocation() {return location;}

/*        void set(string _) {=_;isBad=false;}
        string get() {return ;}

        void set(string _) {=_;isBad=false;}
        string get() {return ;}

        void set(string _) {=_;isBad=false;}
        string get() {return ;}

        void set(string _) {=_;isBad=false;}
        string get() {return ;}
*/
        void sethours(int _hours) {hours=_hours;isBad=false;}
        int gethours() {return hours;}

        void sethourlyRate(double _hourlyRate) {hourlyRate=_hourlyRate;isBad=false;}
        double gethourlyRate() {return hourlyRate;}

        //shift-in and shift-out I/O operators. must define as friends and not direct members.
        friend istream& operator>>(istream& is, class CEmployee& ce) {
            char line[128000+1];
            if (is.good() && !is.eof()) {
                do {
                    is.getline(line, 128000);
                } while (is.good() && !is.fail() && !is.eof() && ('\0'==line[0] || '\n'==line[0]));
            }
            if (!is.good() || is.eof() || '\0'==line[0] || '\n'==line[0]) {
                ce.initialize();
                is.clear(ios_base::badbit|ios_base::failbit);
                return is;
            }
            line[64999]='\0';
            stringstream ss;
            string sLine=line;
            int     id           ;
            string  lastName     ,
                    firstName    ,
                    middleName   ,
                    address1     ,
                    address2     ,
                    city         ,
                    stateProvince,
                    postalCode   ,
                    country      ,
                    department   ,
                    mailstop     ,
                    location     ;
            int     hours        ;
            double  hourlyRate   ;
            ss.str(sLine); //convert line to stringstream
            //input the record
            if (ss.good()) {
                ss >> id
                   >> lastName
                   >> firstName
                   >> middleName
                   >> address1
                   >> address2
                   >> city
                   >> stateProvince
                   >> postalCode
                   >> country
                   >> department
                   >> mailstop
                   >> location
                   >> hours
                   >> hourlyRate
                   ;
                if (!ss.fail()) {


                    //        id
                    _tospaces(lastName     );
                    _tospaces(firstName    );
                    _tospaces(middleName   );
                    _tospaces(address1     );
                    _tospaces(address2     );
                    _tospaces(city         );
                    _tospaces(stateProvince);
                    _tospaces(postalCode   );
                    _tospaces(country      );
                    _tospaces(department   );
                    _tospaces(mailstop     );
                    _tospaces(location     );
                    //        hours
                    //        hourlyRate
                    /*_tospaces();
                    _tospaces();
                    _tospaces();
                    _tospaces();
                    _tospaces();*/

                    //set the object's values using the interface provided
                    ce.setid                  (id                  );
                    ce.setlastName            (lastName            );
                    ce.setfirstName           (firstName           );
                    ce.setmiddleName          (middleName          );
                    ce.setaddress1            (address1            );
                    ce.setaddress2            (address2            );
                    ce.setcity                (city                );
                    ce.setstateProvince       (stateProvince       );
                    ce.setpostalCode          (postalCode          );
                    ce.setcountry             (country             );
                    ce.setdepartment          (department          );
                    ce.setmailstop            (mailstop            );
                    ce.setlocation            (location            );
                    ce.sethours               (hours               );
                    ce.sethourlyRate          (hourlyRate          );
                    /*ce.set                    (                    );
                    ce.set                    (                    );
                    ce.set                    (                    );
                    ce.set                    (                    );
                    ce.set                    (                    );
                    ce.set                    (                    );
                    ce.set                    (                    );*/
                } else {
                    ce.initialize();
                    is.clear(ios_base::badbit|ios_base::failbit);
                }
            } else {
                ce.initialize();
                is.clear(ios_base::badbit|ios_base::failbit);
            }
            return is;
        }
        friend ostream& operator<<(ostream& out, class CEmployee& ce) {
            out <<           ce.getid             ()  << " "
                << spacesto_(ce.getlastName       ()) << " "
                << spacesto_(ce.getfirstName      ()) << " "
                << spacesto_(ce.getmiddleName     ()) << " "
                << spacesto_(ce.getaddress1       ()) << " "
                << spacesto_(ce.getaddress2       ()) << " "
                << spacesto_(ce.getcity           ()) << " "
                << spacesto_(ce.getstateProvince  ()) << " "
                << spacesto_(ce.getpostalCode     ()) << " "
                << spacesto_(ce.getcountry        ()) << " "
                << spacesto_(ce.getdepartment     ()) << " "
                << spacesto_(ce.getmailstop       ()) << " "
                << spacesto_(ce.getlocation       ()) << " "
                <<           ce.gethours          ()  << " "
                <<           ce.gethourlyRate     ()  << endl;
            return out;
        }
        void prettyprint(ostream& out) {
            out << id            << " "
                << lastName      << " "
                << firstName     << " "
                << middleName    << " "
                << address1      << " "
                << address2      << " "
                << city          << " "
                << stateProvince << " "
                << postalCode    << " "
                << country       << " "
                << department    << " "
                << mailstop      << " "
                << location      << " "
                << hours         << "hrs $";
            //  << hourlyRate    << "hrs $";
            out.width(3);
            out.setf(ios::fixed);
            out.precision(5);
            out << hourlyRate;
            out.setf(ios::floatfield);
            out.precision(1);
            out.width(1);
            out << endl;
        }
};


//this function strips _ out of strings.
//this allows strings that would normally have spaces in them to be coded with
//underscroes instead so that stringstream does not
void _tospaces(string& s) {
    unsigned i;
    string s2;
    if (0 == s.compare(".")) {
        s="";
        return;
    }
    for (i=0; i < s.length(); i++) {
        if ('_'==s[i]) {
            s2 += ' '; //replace _ with a space
        } else {
            s2 += s[i]; //append the current character
        }
    }
    s=s2; //assign string back to original
}

//this function converts spaces to _ in strings.
//this allows strings that would normally have spaces in them to be coded with
//underscores instead so that stringstream does not
//interpret the space as an argument separator like it normally does
//(it needs to be a string made of non-whitespace characters).
string spacesto_(string s) {
    unsigned i;
    if (0 == s.compare("")) {
        return string(".");
    }
    for (i=0; i < s.length(); i++) {
        if (' '==s[i]) {
             s[i]='_'; //replace _ with a space
        }
    }
    return s;
}



//sorting comparison function for .sort()
//you can make this a more complicated comparison function if you want to sort by
//employee name and then by id instead.
bool sortcomparebynamethenid(CEmployee first, CEmployee second) {
    //sort by employee lastName,firstName,middleName and then by id
    return first.getlastName() < second.getlastName()
       &&  first.getfirstName() < second.getfirstName()
       &&  first.getmiddleName() < second.getmiddleName()
       &&  first.getid() < second.getid();
}

bool sortcomparebyid(CEmployee first, CEmployee second) {
    //sort by simple id comparison
    return first.getid() < second.getid();
}


//just make sure you are working with a copy of your emplyee data file.
//either way, it's a good policy.
//this version reads, sorts, and writes.
//not sure why you are making this so complicated for something that does the same thing.
//implement e as an array or vector.
//why aren't you using .sort() ?

void sortRecById(char * filepath) {
    fstream flatFileDatabase(filepath, ios_base::in|ios_base::out);
    list<class CEmployee> employees; //let's be realistic, these is a collection of employees
    list<class CEmployee>::iterator li;
    CEmployee employeeRecord; //temporary record variable for reading data into collection

    //counting lines
    while(flatFileDatabase.good() && !flatFileDatabase.eof() && flatFileDatabase.fail()) {
        flatFileDatabase >> employeeRecord;
        if (!employeeRecord.bad()) {
            employees.push_back(employeeRecord);
        }
    }




    //it doesn't matter if you sort the employee numbers if they are disconnected from the record!
    //then you just get a bunch of sorted record id's and the
    //why don't you make id a member of e?

    employees.sort(sortcomparebyid); //feed it the compare function we wrote
    //rewrite the whole flat-file database
    flatFileDatabase.clear();
    flatFileDatabase.seekg(0, ios::beg); //reset get file pointer to start of file
    flatFileDatabase.seekp(0, ios::beg); //reset put file pointer to start of file
    flatFileDatabase.clear();
    for(li = employees.begin(); li != employees.end(); li++) {
        flatFileDatabase << *li; //output the CEmployee object pointed to by the iterator li
    }
    flatFileDatabase.close();
}

void sortRecByNameThenId(char * filepath) {
    fstream flatFileDatabase(filepath, ios_base::in|ios_base::out);
    list<class CEmployee> employees; //let's be realistic, these is a collection of employees
    list<class CEmployee>::iterator li;
    CEmployee employeeRecord; //temporary record variable for reading data into collection

    //counting lines
    while(flatFileDatabase.good() && !flatFileDatabase.eof() && flatFileDatabase.fail()) {
        flatFileDatabase >> employeeRecord;
        if (!employeeRecord.bad()) {
            employees.push_back(employeeRecord);
        }
    }




    //it doesn't matter if you sort the employee numbers if they are disconnected from the record!
    //then you just get a bunch of sorted record id's and the
    //why don't you make id a member of e?

    employees.sort(sortcomparebynamethenid); //feed it the compare function we wrote
    //rewrite the whole flat-file database
    flatFileDatabase.clear();
    flatFileDatabase.seekg(0, ios::beg); //reset get file pointer to start of file
    flatFileDatabase.seekp(0, ios::beg); //reset put file pointer to start of file
    flatFileDatabase.clear();
    for(li = employees.begin(); li != employees.end(); li++) {
        flatFileDatabase << *li; //output the CEmployee object pointed to by the iterator li
    }
    flatFileDatabase.close();
}

void show(char * filepath) {
    fstream flatFileDatabase(filepath, ios_base::in);
    CEmployee employeeRecord; //temporary record variable for reading data into collection

    //counting lines
    flatFileDatabase.seekg(0, ios::beg); //reset get file pointer to start of file
    cout<<"-----Employee Records Start-----"<<endl;
    while(flatFileDatabase.good()) {
        flatFileDatabase >> employeeRecord;
        if (!flatFileDatabase.bad()) {
            employeeRecord.prettyprint(cout); //this is the friend function we defined in the class.
        }
    }
    cout<<"-----Employee Records End-----"<<endl;
    flatFileDatabase.close();
}

int main(void) {
#if defined(TEST)
    //test sortcomparebyid
    CEmployee c(
            903,
            "Farminn",
            "Janieee",
            "Whozitz",
            "999 Zipp Rd",
            "Rt 6",
            "Anywhere",
            "KY",
            "98765-4321",
            "USA",
            "Administration",
            "AD01",
            "JL02",
            38,
            20.00
        ), d(
            23,
            "Palooka",
            "Joe",
            "Harva",
            "123 blooky lane",
            "",
            "Blastoff",
            "PA",
            "12345-6789",
            "USA",
            "Shipping",
            "MS-T12",
            "DH71",
            40,
            9.5
        );

    cout<<sortcomparebyid(c,d);
    cout<<sortcomparebyid(d,c)<<endl;

    //test the CEmployee
    cout<<c;
    cout<<"id lastName firstName middleName address1 address2 city stateProvince postalCode country department mailstop location hours hourlyRate"<<endl;
    cin>>c;
    cout<<c;
#endif

    //test sortRec
    char flatFileDatabasepath[]="employee.txt";

    cout<<"unsorted"<<endl;
    show(flatFileDatabasepath);

    sortRecById(flatFileDatabasepath);

    cout<<"sorted by id"<<endl;
    show(flatFileDatabasepath);

    /*sortRecByNameThenId(flatFileDatabasepath);
    cout<<"sorted by name then id"<<endl;
    show(flatFileDatabasepath);*/

    return 0;
}

Thanks Sir!... i really appreciated your time and effort.... Your'e a pro... keep it up :)


-Dianne-

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.