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
|
# include <iostream>
# include <list>
# include <string>
# include <fstream>
# include <sstream>
//using namespace std;
//https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
class candidateType
{
public:
template <typename charT, typename traits> //overload insertion operator
friend inline std::basic_istream <charT, traits>&
operator >> (std::basic_istream <charT, traits> & inFile, candidateType& c);
template <typename charT, typename traits> //overload output operator
friend inline std::basic_ostream <charT, traits>&
operator << (std::basic_ostream <charT, traits> & outFile, const candidateType& c);
candidateType(const std::string& firstName , const std::string& lastName)
: m_firstName(firstName), m_lastName(lastName){} //member initialization
private:
std::string m_firstName;
std::string m_lastName;
//give your variables meaningful names rather than unnecessary comments
};
template <typename charT, typename traits>
inline std::basic_istream <charT, traits>&
operator >>(std::basic_istream<charT, traits> & inFile, candidateType& c)
{
inFile >> c.m_firstName >> c.m_lastName;
return inFile;
}
template <typename charT, typename traits>
inline std::basic_ostream <charT, traits>&
operator << (std::basic_ostream <charT, traits> & outFile, const candidateType& c)
{
outFile << c.m_firstName << " " << c.m_lastName;
return outFile;
}
template <typename charT, typename traits>
void getData(std::basic_istream<charT, traits>& inFile, std::list<candidateType>& c)
{
if(inFile)
{
std::string line;
while (getline(inFile, line))
{
std::istringstream stream{line};
std::string firstName, lastName;
if(stream)stream >> firstName >> lastName;
if(inFile)
{
c.emplace_front(candidateType(firstName, lastName));
}
}
}
else
{
std::cout << "could not open file \n";
}//let getData() handle file non-openings
}
int main()
{
std::list <candidateType> candidates;
std::ifstream inFile{"C:\\test.txt"};
//std::ifstream object can be initialized directly
//the file is opened when it's associated ifstream object is initialized and
//closed, if still open, when the object goes out of scope
getData(inFile, candidates);
for (const auto& elem : candidates)std::cout << elem << "\n";
}
|