-
help with file i/o
I have a file called accounts.txt that I am trying to read information from. An example of the contents are:
C A 25.00
D B 5.00
C B 6.00
C A 3.00
The real size of the file is not known, other than there are 3 columns, two char and one double. I need to put all of the data into 3 different arrays. When I read from the file, will the data be read from top to bottom like I want it? Also, how can I tell when I am at the bottom of the column and how do I switch to the other column? Thanx.
-
This file is in text format, I assume? Does it have to be? Text I/O sucks.
Best bet would probably be to read the file one line at a time and parse what you get into the three separate columns. Just check for EOF when reading to know when you've reach the End... Of File.
-
use streams (in fstream), use vectors (in the STL).
have a stream read data into a buffer, and if the data is legit, create a new entry in the vector to hold the data.
-
The file will be read from left to right, not top to bottom. Here is an example using c++ streams.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
char a[300];
char b[300];
double c[300];
int n, i;
ifstream in("values.txt");
if (!in)
{
cout << "File not found." << endl;
return 0;
}
n = 0;
while (in >> a[n] >> b[n] >> c[n])
n++;
for (i=0; i<n; i++)
cout << a[i] << " " << b[i] << " " << c[i] << endl;
in.close();
return 0;
}