Harry Overs said:
I'm using the ifstream to read the contents of a file using the >>
operators.
However the problem that I have is that the file is made up of double and
string variables. Is there an easy way to read both types in
Yes, but you'll need to know in advance the exact format of the
data, and depend upon it being correct or make sure bad data is
handled properly.
std::ifstream in("filename");
double d;
std::string s;
in >> d >> s; // read a double, then a string
But if the characters making up the 'double' value are invalid,
'in >> d' will fail, leaving those characters in the stream,
and setting the stream to a 'fail' state, in which it will stay
until you specifically reset it. Another problem is that if
any of your strings contain whitespace, 'in >> s' will stop
reading at the first one. E.g input of "John Doe" will cause
extraction of only "John".
or should I
just read it all in as char* and then convert to the correct format?
Almost. Change 'char*' to 'std::string', and I agree.
IMO this is the best method to 'default' to. You get better control.
A function such as 'strtod()' can do the numeric conversions and has good
error reporting.
while stream state == good
Read a line.
Convert (if numeric) and store.
go to 1
if stream state != eof
read error
-Mike