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;
}
| |