ifstream into a vector
Oct 22, 2011 at 3:10am UTC
So in a nutshell I need to read from a file a set of data, and I want to put that data into a vector. We had a lab where something similar was done, but I just can't seem to wrap my head around how it works exactly.
I can't figure out how to do a loop that will read up to a certain amount of data from the file, put that into a vector, and repeat until it reaches the end of file.
If anybody can explain this concept to me I would greatly appreciate it.
Here's my code for my customer header
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
class customer {
public :
void print_all(customer* x);
customer(string fn, string ln, double bal, int acct,int pin)
: first_name(fn),last_name(ln),balance(bal),account_number(acct), pin_number(pin) {}
string get_fn() {return first_name;}
string get_ln() {return last_name;}
int get_pin() {return pin_number;}
double get_bal() {return balance;}
int get_acct() {return account_number;}
void put_fn(string n) {first_name=n;}
void put_ln(string n) {last_name=n;}
void put_pin(int n) {pin_number=n;}
void put_bal(double n) {balance=n;}
void put_acct(int n) {account_number=n;}
void disp_customer();
void deposit(double n);
void withdraw(double n);
vector<customer> cust;
private :
string first_name;
string last_name;
int pin_number;
double balance;
int account_number;
};
void customer::disp_customer()
{
cout<<"Account #:" <<get_acct()<<endl;
cout<<"Name:" <<get_fn()<<" " <<get_ln()<<endl;
cout<<"Current Balance:" <<get_bal()<<endl;
}
istream& operator >>(istream& is,customer& c)
{
char ch;
string fn,ln;
int acct,pin;
double bal;
is>>ch>>acct>>ch>>ch>>fn>>ch>>ch>>ln>>ch>>ch>>bal>>ch>>ch>>pin>>ch;
c.put_fn(fn);
c.put_ln(ln);
c.put_pin(pin);
c.put_acct(acct);
c.put_bal(bal);
return is;
}
ostream& operator <<(ostream& os, customer& c)
{
return os<<"{" <<c.get_acct()<<"} {" <<c.get_fn()<<"} {" <<c.get_ln()<<"} {" <<c.get_bal()<<"} {" <<c.get_pin()<<"} " ;
}
void customer::withdraw(double n)
{
double a=0;
cout<<"Current balance\n\n$" <<n<<"\n\n" ;
cout<<"Withdrawal ammount:" ;
cin>>a;
n=n-a;
cout<<"\nCurrent balance after withdrawal:$" <<n<<"\n\n" ;
}
Oct 22, 2011 at 2:31pm UTC
see std::copy and std::istream_iterator, and std::back_inserter
1 2
vector<customer> data;
copy(istream_iterator<customer>(cin), istream_iterator<customer>(), back_inserter(data));
Topic archived. No new replies allowed.