1
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>

using namespace std;

int main()
{
    srand(time(0));
    const int array_size=10,n=10;
    int i,j,k;
    fstream io("io.dat", ios_base::binary);
    float a[array_size];
    for (i=0;i<n;i++) {
        cout<<"Inputting "<<i+1<<" array:\n";
        for (j=0;j<array_size;j++) {
            a[j]=(float)rand()/(RAND_MAX+1)*200-100;
            cout<<i+1<<"["<<j<<"]="<<a[j]<<endl;
        }
        io.write((char *)&a,sizeof(a));
    }
    io.close();
    io.open("io.dat", ios_base::binary);
    j=1;
    while (!io.eof()) {
        cout<<"Reading "<<j<<" array:"<<endl;
        io.read((char *)&a,sizeof(a));
        for (i=0,k=0;i<array_size;i++) {
            cout<<j<<"["<<i<<"]="<<a[i]<<endl;
            if (a[i]<0) k++;
        }
        cout<<"Number of negative elements in "<<j++<<" array="<<k<<endl;
    }
    return 0;
}

I am stuck in reading arrays from binary file. The problem is that condition of breaking reading cycle doesn't even works. Program reads the same array again and again.

rakodeel
  • 19
  • 1
  • eof as loop continuation condition is almost always wrong. instead use streams state after read operation. – Cheers and hth. - Alf Mar 15 '15 at 09:08
  • 4
    Don't use e.g. `!in.eof()` as loop condition, the `eofbit` flag will not be set until *after* you try to read from beyond the end of the file. That will cause the loop to iterate once to many. Instead if you read e..g [this `read` reference](http://en.cppreference.com/w/cpp/io/basic_istream/read) you will see that it returns the stream, and you can use the stream as a boolean condition, like `while (in.read(...))` – Some programmer dude Mar 15 '15 at 09:10
  • @JoachimPileborg is right. [Read this!](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) – notadam Mar 15 '15 at 10:05

1 Answers1

0

This sort of a problem is caused because you are using !in.eof(). One of the easiest way to solve this is to read inside the while loop like in this code

io.open("io.dat", ios_base::binary);
j=1;
while ( io.read( (char *) &a, sizeof(a) ) )    //  changed the !in.eof
 {
    cout<<"Reading "<<j<<" array:"<<endl;  
    // Removed the read form here
    for (i=0,k=0;i<array_size;i++) 
     {
        cout<<j<<"["<<i<<"]="<<a[i]<<endl;
        if (a[i]<0) k++;
     }
    cout<<"Number of negative elements in "<<j++<<" array="<<k<<endl;
 }

Well, that should solve the problem with your output.

Arun A S
  • 6,421
  • 4
  • 29
  • 43