i want to learn OOP programing.specialy oprater overloading

i want to learn oprater overloading

A common student 'overload' ...

is, overloading operator <<

to output the data in a (student) data set ...

See the following:

Data file: myData.txt

1 20000101 Jane Doe
4 19711203 Hannah Mariam Johnston
2 19900303 Joe
3 19990324 James Harry Robinson

Program:

// simpleVecStructFromFile.cpp // 2013-03-23 //

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include <cctype> // re. isspace

using namespace std;

const string FNAME = "myData.txt";

struct Student
{
    int id;
    int dob;
    string name;

    // default ctor
    Student() : id(0), dob(0) {}

    // def'n of overloaded << for Student obj's ...
    friend ostream& operator << ( ostream& os, const Student& s )
    {
        return os << s.id << ", " << s.dob << ", " << s.name;
    }
} ;

// show whole vector v ... uses above def'n of overloaded << for Student obj  
ostream& operator << ( ostream& os, const vector < Student >& v )
{
    int i= 0, len = v.size();
    for( ; i < len ; ++ i )
        os << v[i] << endl;
    return os;
}

void ltrim( string& s )
{
    int i = 0, len = s.size();
    while( i < len && isspace(s[i]) ) ++i;
    s.erase( 0, i );
}



int main()
{

    ifstream fin( FNAME.c_str( ));
    if( fin )
    {
        vector < Student > v;          // construct empty Student vector v
        string line;
        while( getline( fin, line ) ) // get this whole line & 'eat' '\n' at end
        {
            istringstream iss( line );// construct iss obj from line
            Student s;                // get empty Student struct, calls ctor
            iss >> s.id >> s.dob;     // skips over leading ws
            getline( iss, line );     // preserves leading ws
            ltrim( line );            // trim any/all leading ws
            s.name = line;            // set name
            v.push_back( s );         // Ok .. add this Student to vector
        }
        fin.close();

        // Ok ... show the vector ... v ...
        cout << "Your file contained:\n" << v;
    }
    else
        cerr << "There was a problem opening file " << FNAME << endl;

    cout << "\nPress 'Enter' to continue/exit ... " << flush;   
    cin.get();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.