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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
// text file:
// 10101 Mike Sanderson
// 10202 Bart Simpson
// 10105 Lisa Simpson
// 30304 Homer Simpson
#include <algorithm>
#include <fstream>
#include <iostream>
#include <istream>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
struct Student {
int num_reg {};
std::string name;
std::string surname;
Student() = default;
Student(std::string line);
//friend:
friend bool operator== (const Student& lhs, const Student& rhs);
friend bool operator== (const Student& lhs, int num_reg);
friend std::ostream& operator<< (std::ostream& os, const Student& rhs);
};
Student::Student(std::string line)
{
std::istringstream iss { line };
iss >> num_reg >> name >> surname;
}
bool operator== (const Student& lhs, const Student& rhs)
{
return std::tie(lhs.num_reg, lhs.name, lhs.surname)
== std::tie(rhs.num_reg, rhs.name, rhs.surname);
}
bool operator== (const Student& lhs, int num_reg)
{
return lhs.num_reg == num_reg;
}
std::ostream& operator<< (std::ostream& os, const Student& rhs)
{
os << rhs.num_reg << ' ' << rhs.name << ' ' << rhs.surname;
return os;
}
std::unique_ptr<std::basic_istream<char>> getStream(const std::string& fname);
std::vector<Student> populateFromStream(std::basic_istream<char>& bis);
void printVec(const std::vector<Student>& v);
int main()
{
auto students { populateFromStream( *getStream("test") ) };
printVec(students);
auto mike { std::find(students.begin(), students.end(), 10101) };
if (students.end() != mike) {
std::cout << "Found:\n" << *mike << '\n';
}
}
std::unique_ptr<std::basic_istream<char>> getStream(const std::string& fname)
{
if (fname == "test") {
return std::make_unique<std::istringstream>(
"10101 Mike Sanderson\n"
"10202 Bart Simpson\n"
"10105 Lisa Simpson\n"
"30304 Homer Simpson\n"
);
} else {
return std::make_unique<std::ifstream>( fname );
}
}
std::vector<Student> populateFromStream(std::basic_istream<char>& bis)
{
std::vector<Student> v;
for (std::string line; std::getline(bis, line); /**/) {
Student s(line);
v.push_back(s);
}
return v;
}
void printVec(const std::vector<Student>& v)
{
std::cout << "Students:\n";
for (const auto& e: v) {
std::cout << e << '\n';
}
std::cout << '\n';
}
|