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 72 73 74 75 76 77 78 79 80 81
|
#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
// This is our record
struct Record
{
string name;
int age;
float gpa;
};
// How do we read each record
istream& operator >> (istream &s, Record &r)
{
string line;
if (getline(s, line))
{
stringstream ss(line);
// read the name
getline(ss, r.name, '/');
// convert to uppercase
std::transform(r.name.begin(), r.name.end(),
r.name.begin(),
(int (*)(int))toupper);
// rest of the data
ss >> r.age >> r.gpa;
}
return s;
}
bool copyRecords(vector<Record> &records, const string &fname)
{
records.clear();
fstream fs(fname.c_str());
if (fs)
{
// copy all the records from file
copy(istream_iterator<Record>(fs), istream_iterator<Record>(),
back_inserter(records));
return true;
}
return false;
}
// How do we print the record
ostream& operator << (ostream &s, const Record &r)
{
cout << r.name << " " << r.age << "/" << r.gpa;
return s;
}
void display(const vector<Record> &records)
{
// copy all the records to screena
copy(records.begin(), records.end(), ostream_iterator<Record>(cout, "\n"));
}
int main(void)
{
vector<Record> records;
if (copyRecords(records, "record.txt"))
{
display(records);
}
return 0;
}
|