fstream tokens into a vector

Nov 9, 2008 at 2:46am
Hi,
Im trying to write a simple class who's main reads in information about employees from data file called emp.dat.
In the data file emp.dat employee info is of the form for a number of employees:
TEMP
Jone Kane
£500

FULL
Jane Wall
£450

etc

What I trying to do is find a way to read each token/string from the file and store the contents in the following variables,
EmpType
Name
Wage,
on each iteration of some sort of loop so that I can create an Employee object corresponding to the above for each employee and then store these in a vector.
Hope someone can help me out a bit as im finding it hard to move from Java to C++, do know what methods to invoke on which ohject and the whole pointer thingy is making me dizzy lol ta...
Nov 9, 2008 at 8:45pm
In general for reading from a file you'll want to use an ifstream.
1
2
3
4
#include <fstream>
ifstream infile;

infile.open("emp.dat")


Then you have two choices (at least) for reading in your data. Given that you're reading in a string, empName. (be sure to #include <string> ),
1
2
3
4
string empName;
while (infile >> empName) {
//do some stuff
}

or you can use getline,
1
2
3
while(getline(infile, empName)) {
//do some stuff
}

You'll have to then do some manipulations to handle the structure of your data. If your data file has more than one entry on a line then the first method is nice because you can do while(infile >> var1 >> var2 >> var 3) up to as many entries you have (your variables have to have the right type of course). getline reads the entire line into a string, but then you can do more complicated things with the string.
Nov 10, 2008 at 8:19pm
Thanks that helped alot cheers...
Topic archived. No new replies allowed.