So I decided to do the phonebook thing in c++. This reads a file, stores it, sorts it, and then writes it. I have my own implementation for sort, but for readability I have used the STL sort in what I'm posting here. I also need to clean up the output using iomanip, but this is fine. Searching to find a name is just implementing a custom find(), wouldn't be difficult but I didn't include it.
#include <iostream>
#include <vector>
#include <istream>
#include <fstream>
#include <ostream>
#include <iomanip>
#include <algorithm>
using namespace std;
class record {
public:
record() {}
bool operator<(const record &)const;
friend istream& operator>>(istream &, record &);
friend ostream& operator<<(ostream &, const record &); // friend declarations
private:
string firstname;
string lastname;
string phonenum;
};
bool record::operator<(const record & values)const{
if (lastname < values.lastname)
return true;
if(lastname == values.lastname && firstname < values.firstname)
return true;
}
istream & operator>>(istream &in, record & values){
in >> values.firstname >> values.lastname >> values.phonenum;
}
ostream & operator<<(ostream &out, const record & values){
out << left << values.lastname << " " << values.firstname << " " << values.phonenum;
}
int main(int argc, char *argv[]) {
string line, firstname, lastname, phonenum;
record values;
vector<record> A;
if(argc < 2){
cerr << "Incorrect usage, please try again at a later time. Optionally, do not try again and go directly to ja\
il. Do not pass go, do not collect 200 dollars." << endl; // parse command-line arguments
}
ifstream in(argv[1]); // open file
while(in >> values){
A.push_back(values);
}
in.close(); // close file
sort(A.begin(), A.end()); // sort data
for(int i = 0; i < A.size(); i++){
cout << A[i] << endl; // write data to stdout { array index [] based }
}
}