[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: C++ programming: keeping count of data items read from file

H.S. wrote:

In a C++ program I am reading a data file for later processing and computations. While reading that data file, I want to keep track of data items (doubles) read.

The data file is just a text file with N lines with C doubles in each line (N and C are known a priori). For now, I just read from the file stream in to a 2D array variable by reading each double at a time.

Now I am trying to introduce some sanity checking into this reading block. Here is what I am trying to do: 1. Verify how many doubles I have read in each line. Must be C. If they are not C, then the input file is corrupt. 2. Verify that the total number of data items are NxC. This is simple, I just keep a track of how many numbers I have read.

So, how do I go about doing (1) above? I was thinking of somehow checking if I have reached the end of line somehow (EOL?) but haven't found a method to do so. All I have found is EOF.


Not directly helpful, but some suggestions:

1. You might want to learn PERL or Python or Ruby, and do it there.
2. If it has to be C++, learn enough PERL to write a filter for the data file, and transform it so that it has one double per line. 3. Debug the data generator /in situ/ with a good debugger, and bypass the need to do the sanity checking.
4. Find a good C++ reference, and use it.  There are several.

Slightly more helpful:

1. Read one line at a time in as a string, then operate on the string.
2. C++ has the ability to do everything that C does in a low level way, but why? Use the C++ way, or use the C way:

#include <cstdio>
#include <iostream>
. . .
using namespace std;
. . .
ios::sync_with stdio();
. . .
int blah = fscanf(somefile,"%f %f %f %f\n", d1,d2,d3,d4);
if (blah != correctvalue)
    cout << "error in data file\n";
. . .
// etc.

(The ios::sync_with_stdio(); line may differ slightly on different C++ implementations. I haven't used it in a while. May be spelled synch_. Too lazy to look it up.

The fscanf line may just be wrong. I quit writing C programs years ago. Too old, memory failing.)

Mark Allums

Reply to: