C++ examples for File Stream:stream
Reading Time class objects from a file.
#include <iostream> #include <fstream> #include <string> #include <iomanip> using std::string; class Time/*from ww w.ja va 2 s .c o m*/ { private: int hours {}; int minutes {}; int seconds {}; public: Time() = default; Time(int h, int m, int s); int getHours()const { return hours; } int getMinutes()const { return minutes; } int getSeconds()const { return seconds; } friend std::istream& operator>> (std::istream& in, Time& rT); // Friend extraction operator }; std::ostream& operator <<(std::ostream& out, const Time& rT); // Overloaded insertion operator declaration // Constructor Time::Time(int h, int m, int s) { seconds = s%60; // Seconds left after removing minutes minutes = m + s/60; // Minutes plus minutes from seconds hours = h + minutes/60; // Hours plus hours from minutes minutes %= 60; // Minutes left after removing hours } // Insertion operator std::ostream& operator <<(std::ostream& out, const Time& rT) { out << ' ' << rT.getHours() << ':'; char fillCh {out.fill('0')}; // Set fill for leading zeros out << std::setw(2) << rT.getMinutes() << ':' << std::setw(2) << rT.getSeconds() << ' '; out.fill(fillCh); // Restore old fill character return out; } // Extraction operator std::istream& operator>> (std::istream& in, Time& rT) { char ch {}; // Stores ':' in >> rT.hours >> ch >> rT.minutes >> ch >> rT.seconds; // Ensure seconds and minutes less than 60 rT.minutes += rT.seconds/60; rT.hours += rT.minutes/60; rT.minutes %= 60; rT.seconds %= 60; return in; } int main() { string fileName; std::cout << "Enter the name of the file you want to read, including the path: "; std::getline(std::cin, fileName); std::ifstream inFile {fileName}; if(!inFile) { std::cerr << "Failed to open input file. Program terminated.\n"; exit(1); } Time period; int count {}; const int perline {5}; std::cout << "Times on file are:\n"; while(!(inFile >> period).eof()) { std::cout << period; if(!(++count % perline)) std::cout << std::endl; // Newline every 5th output } std::cout << std::endl; inFile.close(); }