Muutetaan vielä tuotteiden lukua oliomaisemmaksi, eli annetaan tuotteelle kuuluvat tehtävät kokonaan tuote- luokan vastuulle, samalla lisätään tuotteet- luokka.
// luerek.cpp - esimerkki oliosta joka käsittelee tiedostoa
// Vesa Lappalainen -96,-01
// Projektiin +ALI\mjonot.c
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "mjonotpp.h"
#include "dosout.h"
using namespace std;
//---------------------------------------------------------------------------
class cTuote {
string nimike;
double hinta;
int kpl;
void alusta() { nimike=""; hinta=0.0; kpl=0; }
public:
cTuote() { alusta(); }
int setAsString(string &st) {
string pala;
alusta();
nimike = erota(st,'|'); poista_tyhjat(nimike); if ( nimike == "" ) return 1;
pala = erota(st,'|'); if ( !luvuksi(pala,hinta) ) return 1;
pala = erota(st,'|'); if ( !luvuksi(pala,kpl) ) return 1;
return 0;
}
ostream &tulosta(ostream &os) const {
ios::fmtflags oldf = os.setf(ios::left);
os << setw(20) << nimike << " " << setiosflags(ios::right)
<< setw(7) << hinta << " "
<< setw(4) << kpl;
os.flags(oldf);
return os;
}
};
//----------------------------------------------------------------------------
class cTuotteet {
string nimi;
public:
cTuotteet(const char *n) { nimi = n; }
int tulosta(ostream &os) const;
};
int cTuotteet::tulosta(ostream &os) const
{
cTuote tuote;
string rivi;
ifstream f(nimi.c_str()); if ( !f ) return 1;
cout << "\n\n\n";
cout << "-------------------------------------------" << endl;
while ( getline(f,rivi) ) {
if ( tuote.setAsString(rivi) ) continue;
tuote.tulosta(os); os << endl;
}
cout << "-------------------------------------------\n";
cout << "\n\n\n" << endl;;
return 0;
}
//----------------------------------------------------------------------------
int main(void)
{
cTuotteet tuotteet("tuotteet.dat");
if ( tuotteet.tulosta(cout) ) {
cout << "Tuotteita ei saada luetuksi!" << endl;
return 1;
}
return 0;
}