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
|
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
#include <fstream>
enum class Food {
Pizza = 0, Apple = 1, Pasta = 2, Rice = 3, Bacon = 4, Cake = 5, count = 6
};
// i/o facilities for Food (error-handling elided for brevity)
const std::string food_names[std::size_t(Food::count)] = {
"Pizza", "Apple", "Pasta", "Rice", "Bacon", "Cake"
};
std::ostream& operator<< ( std::ostream& stm, Food f ) {
return stm << food_names[ std::size_t(f) ] ;
}
std::istream& operator>> ( std::istream& stm, Food& f ) {
std::string fname ;
if( stm >> fname )
f = Food( std::find( std::begin(food_names), std::end(food_names), fname ) - std::begin(food_names) ) ;
return stm ;
}
struct Register {
std::string name;
int age = 0 ;
std::string quote;
std::vector<Food> favourite_foods;
};
// i/o facilities for Register
std::ostream& operator<< ( std::ostream& stm, const Register& r ) {
stm << r.name << '\n' // name on the first line
<< r.age << '\n' // age as a string on the second line
<< r.quote << '\n' ; // quote on the third line
for( Food f : r.favourite_foods ) stm << f << ' ' ; // favorite foods on the fourth line
return stm << '\n' ; // and an empty line to signal the end
}
std::istream& operator>> ( std::istream& stm, Register& r ) {
// read the first non-empty line into the name
while( std::getline( stm, r.name ) && r.name.empty() ) ;
stm >> r.age // read the age from the next line
>> std::ws ; // extract and discard the new line
std::getline( stm, r.quote ) ; // read the quote from the next line ;
// read favourite foods from the next line
std::string foods_line ;
std::getline( stm, foods_line ) ;
std::istringstream string_stm(foods_line) ;
r.favourite_foods.clear() ;
Food f ;
while( string_stm >> f ) r.favourite_foods.push_back(f) ;
return stm ;
}
int main() {
Register johnny {
"Johnny",
20,
"Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.",
{ Food::Pizza, Food::Bacon, Food::Cake }
};
Register hodges {
"Johnny Hodges",
37,
"<put some appropriate quote here>",
{ Food::Pasta, Food::Rice, Food::Apple, Food::Pizza }
};
std::cout << johnny << '\n' << hodges << '\n' ; // write to stdout
std::ofstream( "people.txt" ) << johnny << '\n' << hodges << '\n' ; // write to file
{
// read back from file and print what was read
std::cout << "information read back from the file:\n--------------\n" ;
Register johnny_2, hodges_2 ;
if( std::ifstream( "people.txt" ) >> johnny_2 >> hodges_2 ) // read from file
std::cout << johnny_2 << '\n' << hodges_2 << '\n' ; // and write to stdout
}
}
|