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
|
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
struct film
{
std::string name ;
std::string director ;
std::string year ;
std::string language ;
};
// write to an output stream
std::ostream& operator<< ( std::ostream& stm, const film& f )
{
// write one string per line, end with a blank line
return stm << f.name << '\n' << f.director << '\n' << f.year << '\n' << f.language << "\n\n" ;
}
// read from an input stream
std::istream& operator>> ( std::istream& stm, film& f )
{
// read one line per string, ignore blank lines at the beginning
// read the first line, after skipping over blank lines
while( std::getline( stm, f.name ) && f.name.empty() ) ;
// read the remaining lines
if( std::getline( stm, f.director ) && std::getline( stm, f.year ) && std::getline( stm, f.language ) ) ; // do nothing more
else f = {} ; // clear all fields in f
return stm ;
}
int main()
{
const std::string file_name = "films.txt" ;
{
const std::vector<film> favourites = { { "Au hasard Balthazar", "Bresson", "1966", "French" },
{ "Stalker", "Tarkovsky", "1979", "Russian" },
{ "Smultronstället", "Bergman", "1957", "Swedish" },
{ "Ikiru", "Kurozawa", "1952", "Japanese" },
{ "Werckmeister harmóniák", "Bela Tarr", "2000", "Hungarian" },
};
std::ofstream file(file_name) ;
for( const film& f : favourites ) file << f ;
}
{
std::vector<film> film_list ;
std::ifstream file(file_name) ;
film f ;
while( file >> f ) film_list.push_back(f) ;
std::cout << film_list.size() << " items were read\n\n" ;
for( const auto& f : film_list ) std::cout << f ;
}
}
|