c++ - Initializing a Vector of Objects from a .txt file -
#include<iostream> #include<vector> #include<fstream> #include "stock.h" int main(){ double balance =0, tempprice=0; string tempstr; vector < stock > portfolio; typedef vector<stock>::iterator stockit; ifstream filein( "results.txt" ); for(stockit = portfolio.begin(); != portfolio.end(); i++) { while ( !filein.eof( )) { getline(filein,tempstr); i->setsymbol(tempstr); filein >> tempprice; i->setprice(tempprice); getline(filein,tempstr); i->setdate(tempstr); } filein.close(); } for(stockit = portfolio.begin(); != portfolio.end(); i++){ cout<<i->getsymbol() <<endl; cout<<i->getprice() <<endl; cout<<i->getdate() <<endl; } return 0; }
sample text file, results.txt:
goog 569.964 11/17/2010 msft 29.62 11/17/2010 yhoo 15.38 11/17/2010 aapl 199.92 11/17/2010 now obviously, want program create vector of stock objects has appropriate set/get functionality object: stock(string, double, string).
once done, want print out each individual member of each object in vector.
one thing boggles mind fstream, how can decipher spaces , end of lines, , intelligently read strings/ints/doubles , place them appropriate data type? maybe can't...and have add entirely new functionality?
now seem i'm not creating new object each iteration of loop? think need along lines of:
portfolio.push_back(new stock(string, double, string));? i'm not entirely sure how point.
also, code should interchangeable std::list std::vector. program compiles without error, however, there 0 output.
first of all, iterating on vector makes sense when isn't empty. remove line:
for(stockit = portfolio.begin(); != portfolio.end(); i++) because otherwise contents of loop never executed.
second, have problems input reading: use getline first field, read values of 3 fields on line tempstr variable.
third, shouldn't use while(!filein.eof()) - eof function returns true after tried read past end of file. instead, use:
while (filein >> symbol >> price >> date) { //here should create stock object , call push_back on vector. } this read 3 fields, separated spaces.
Comments
Post a Comment