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
|
#include <iostream>
#include <string>
#include <sstream>
struct image
{
std::string file_name ;
};
////////////////////// implement i/o functionality for image (image can take care of itself) ///////////
std::ostream& operator<< ( std::ostream& stm, const image& img )
{ return stm << img.file_name << '\n' ; } // add more lines if image has more information
std::istream& operator>> ( std::istream& stm, image& img )
{ return std::getline( stm, img.file_name ) ; }
///////////////////////////////////////////////////////////////////////////////////////////////////////////
struct user
{
std::string name;
image foto; //my class image for images
std::string address;
int age;
};
//////////////////////////////// implement i/o functionality for user //////////////////////////////////
std::ostream& operator<< ( std::ostream& stm, const user& usr ) // one member per line, extra newline at end
{ return stm << usr.name << '\n' << usr.foto << usr.address << '\n' << usr.age << "\n\n" ; }
std::istream& operator>> ( std::istream& stm, user& usr )
{
while( std::getline( stm, usr.name ) && usr.name.empty() ) ; // skip leading empty lines
stm >> usr.foto && std::getline( stm, usr.address ) && stm >> usr.age ;
if( !stm || usr.age < 0 ) { usr = {} ; stm.clear(std::ios_base::failbit) ; }
return stm ;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
int main() // simple test program
{
constexpr std::size_t N = 3 ;
std::stringstream file ;
{
const user users[N] {
{ "joaquim", { "C:\\Nova pasta\\acrobat.bmp" }, "viseu", 23 },
{ "yakim", { "C:\\Nova pasta\\gymnast.bmp" }, "leiria", 7 },
{ "loakim", { "C:\\Nova pasta\\funambulist.bmp" }, "guarda", 86 }
};
for( const auto& a_user : users ) file << a_user << '\n' ;
}
{
std::cout << "the following were read back from stream:\n-----------------\n\n" ;
int cnt = 0 ;
user some_user ;
while( file >> some_user ) std::cout << '#' << ++cnt << ".\n" << some_user << '\n' ;
}
}
|