Reading Data file
Oct 7, 2010 at 12:12am UTC
I always have problems with manipulating strings. To make things short, I want to process the data being fed. I managed to output the data but I don't understand how to process the data...
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
using namespace std;
#include <iostream>
#include <fstream>
#include <string>
int main() {
ifstream filestream;
string filename;
// File existence checking
while (true ) {
cout << "Please input data filepath: " << endl;
cin >> filename;
filestream.open( filename.c_str(), ios::in );
if (filestream.fail()) {
cout << "Unable to access file, please try again." << endl;
}
else {
while (!filestream.eof()) {
string line;
getline ( filestream, A );
cout << A << endl;
}
filestream.close();
break ;
}
}
}
My data looks like this...
1 2 3 4 5
Anchorage, Alaska (March, 2010)
2010-03-01 5:05 3.95
2010-03-01 10:38 28.63
2010-03-01 17:52 1.56
2010-03-01 23:28 25.44
Ignore the first line, it should be easy to get rid of, but I have problems separating each line into 2 different string and 1 integer...
Oct 7, 2010 at 11:51am UTC
Is there some reason why
1 2 3
string a, b;
int c;
filestream >> a >> b >> c;
wouldn't work?
Last edited on Oct 7, 2010 at 11:51am UTC
Oct 7, 2010 at 1:00pm UTC
You should never loop against eof() like this:
1 2 3 4 5
while (!filestream.eof()) {
string line;
getline ( filestream, A );
cout << A << endl;
}
That is because eof() will not be set until after your read failed. So your getline() could contain false information before eof() is checked.
Combining hamsterman's solution you might want to try it this way:
1 2 3 4 5 6
string a, b;
float c;
while (filestream >> a >> b >> c)
{
// do something with a, b and c ...
}
EDIT : whoops, last column is a float, not an int...
Last edited on Oct 7, 2010 at 1:02pm UTC
Oct 8, 2010 at 9:41am UTC
I think this posting on eof() function should be 'sticky' as I can see a lot of poster code not using what Galik said.
I forget the guy who do extensive testing using eof() hahahaa....... he must have gone through sleep-less nights debugging this bugger :P
Topic archived. No new replies allowed.