how to sort inside a text file?

I have a phone book program that takes in contact information, sorts it (using bubble sort in an array list) and outputs the sorted data (last name alphabetically) into a text file. My problem is, the array is successfully sorted, bubble sort works, contact is added successfully, but the contacts are not sorted alphabetically in the text file. They are just inputted in the order they were inputted.

add contact:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void AddressBook::addContact(std::string fName, std::string lName, std::string pNumber, std::string addr) 
{
	// need validation

	if (isFull())
	{
		std::cout << "Is full" << std::endl;
		return;
	}

	Contact *contact = new Contact;

	contact->firstName = fName;
	contact->lastName = lName;
	contact->name = lName + ", " + fName;
	contact->phoneNumber = pNumber;
	contact->address = addr;

	std::cout << contact->name + " has been added!" << std::endl;
	phoneBook[length] = contact;
	appendToFile(phoneBook); //stuff in file not sorted
	length++; 
	bubbleSort(phoneBook, length);
	
}


sorting algorithm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void AddressBook::bubbleSort(Contact * phoneBook[], int n)
{
	Contact* temp;
	int j = 0;

	for (int i = 0; i < length; i++)//for n-1 passes
	{
		for (int j = 0; j < length - 1; j++)
		{
			if (phoneBook[j]->name > phoneBook[j + 1]->name)
			{
				temp = phoneBook[j];
				phoneBook[j] = phoneBook[j + 1];
				phoneBook[j + 1] = temp;
			}
		}
	}
}


append to file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void AddressBook::appendToFile(Contact* phoneBook[])
{
	myFile.open("fileName.txt", std::ios::app);
	if (!myFile)
	{
		std::cerr << "Error: file could not be opened." << std::endl;
		return;
	}

	myFile << std::endl << phoneBook[length]->name << std::endl;
	myFile << phoneBook[length]->phoneNumber << std::endl;
	myFile << phoneBook[length]->address << std::endl;
	std::cout << std::endl << std::endl;

	bubbleSort(phoneBook, length);

	myFile.close();
}
Last edited on
What is length? That reeks of out-of-range error.


You seem to append one entry to a file.
If you have "CDB" in file and append "A", then you have "CDBA" in file.
If you have "CDBA" in memory, sort it to "ABCD" and then write all that to a new file, that file will have "ABCD".


Why does "appendToFile" call "sort"? If it must, why after all the writing?
length is the size of the array. It increments each time I call add contact, and decrements when I delete a contact. I've taken all the precautionary (as far as I know) out of range errors out.

I'm unable to sort the entire list and then append because it adds a contact at once, each time and should update as we add/delete more contacts.

I just removed append from the back, although moving it to the front doesn't help either.
Last edited on
I am not sure I understood your description of a problem properly, but here is my take on this.

Your problem is that you are appending the contacts to the end of a file which already contains the data about contacts. Every sort function you called doesn't affect anything that is already existing inside the file.

What you are supposed to do is:
1. Read and parse the existing phonebook.txt into a Contact[] phoneBook array. At this step, you should have phoneBook containing all records that were inside phonebook.txt.
2. Add new contact to phoneBook.
3. Sort the phoneBook using bubble sort.
4. Write data to a file using flag std::ios::trunc (to remove everything that existed inside a file previously).

Here is an example of writing the contacts to a file without appending, but instead clearing everything there was before and inserting new text.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <string>
#include <fstream>

class Contact {
public:
	Contact(std::string fName, std::string lName) : first_name{ fName }, last_name{ lName } {}
	std::string GetName() const noexcept {
		return first_name + " " + last_name;
	}
private:
	std::string first_name;
	std::string last_name;
};

void BubbleSort(Contact* phoneBook, const int& length)
{	
	for (int i = 0; i < length; i++)//for n-1 passes
	{
		for (int j = 0; j < length - 1; j++)
		{
			if (phoneBook[j].GetName() > phoneBook[j + 1].GetName())
			{
				Contact temp = phoneBook[j];
				phoneBook[j] = phoneBook[j + 1];
				phoneBook[j + 1] = temp;
			}
		}
	}
}

bool WriteContactsToFile(Contact* phoneBook, const int& length) {

        //You can remove the std::ios::out flag, because "ofstream" already has that flag
        //enabled by default
	std::ofstream outFile("phonebook_db.txt", std::ios::out | std::ios::trunc);

	if (!outFile.is_open()) return false;

	BubbleSort(phoneBook, length);

	for (int i = 0; i < length; i++) {
		outFile << phoneBook[i].GetName();
		if (i == length - 1) break;
		outFile << ", ";
	}

	outFile.close();

	return true;
}


int main()
{

	Contact phoneBook[4] = {
		Contact("John", "Smith"),
		Contact("Beta", "Smith"),
		Contact("Alpha", "Smith"),
		Contact("Cee", "Smith")
	};

	std::cout << std::boolalpha << "Updated correctly: " << WriteContactsToFile(phoneBook, 4);

	//Keep console open
	char ch;
	std::cin >> ch;

	return 0;
}


File output:
Alpha Smith, Beta Smith, Cee Smith, John Smith

Topic archived. No new replies allowed.