samedi 31 décembre 2016

Read text file with custom type objects and use istream_iterator?

I need to read in a text file with istream_iterator and seperate it to Customer and Purchase types. Order Objects are defined as (Customer,vector Purchase vP), so every Customer has its own list of Purchases. My problem is that i have to seperate the incoming Order stream to Customer and Purchase Objekt, but the text file has different numbers of Purchases.

//Custom Class Customer,Class Purchase...

class Order {
public:

Order() :
cust(Customer{}), vP(std::vector<Purchase>{}) {
};

Order(Customer c, std::vector<Purchase> v) :
cust{c}, vP{v}
{
    sort(vP.begin(), vP.end());
}

Customer get_cust() const {
    return cust;
}
friend std::ostream& operator<<(std::ostream&, const Order&);
friend std::istream& operator>>(std::istream&, Order&);

// etc.
private:
Purchase pur;
Customer cust;
std::vector<Purchase> vP;
};

ostream& operator<<(std::ostream& out, const Order& o) {
out << o.cust << endl;
for (int i{0}; i < o.vP.size(); i++) {
    out << " " << i + 1 << " " << o.vP.at(i) << endl;
}
return out;
}

// I need help right here... // How can I seperate incoming Objects properly?

istream& operator>>(std::istream& in, Order& o) {

if (in >> o.cust >> o.pur) {
    o.vP.push_back(o.pur);
// I know I have to seperate here...
    return in;
}
}


int main() {

vector<Order> vectOrd;

ifstream inFile("C:\\cpo1.txt");

istream_iterator<Order> eof;
istream_iterator<Order> in_iter(inFile);

    while (in_iter != eof) {
        vectOrd.push_back(*in_iter++);
    }


for (int i{0}; i < vectOrd.size(); i++) {
    cout << "Order: \n" << vectOrd.at(i) << endl;
}

return 0;
}

// This is the Text file that i have to read in

#725454 Schenker Rudolf DE-30159 Hannover
Shirt 135.95 1
Tie 89.59 1
#987654 Orbison Roy US-TN37075 Hendersonville
Mug 1.49 3
T-Shirt 14.90 1
#123456 Petty Tom US-FL32641 Gainesville
Flashlight 12.95 2
#246802 Hite Bob US-CA90291 Venice
CannedBeans 0.89 10
CannedTomatoes 1.79 6
#246802 Hite Bob US-CA90291 Venice
CanOpener 0.48 1
Spoon 1.49 4
Needle 0.05 100
#135791 Lewis Huey US-MT59870 Stevensville
Flux-Compensator 28950.00 1
Comic 1.00 1
BaseballBat 29.00 1
PS4 549.00 1
#725454 Schenker Rudolf DE-30159 Hannover
Yacht 12000000.00 1
LifeSaver 8.95 20
#101112 Cale JJ US-OK73101 Oklahoma-City
Amplifier 534.95 1
Speaker 198.00 4
#555453 Williams Robbie GB-ST01782 Stoke-On-Trent
Radiator 159.00 3
MercedesSLS 264000.00 1
#123124 Waits Tom US-CA91765 Pomona
Banjo 399.00 1
PS4 599.00 1
AudiA8 119500.00 1
#101112 Cale JJ US-OK73101 Oklahoma-City
SpareFuse 0.10 20

// Thanks for every response!

Aucun commentaire:

Enregistrer un commentaire