从二进制文件C ++中读取数组

时间:2015-03-15 09:05:06

标签: c++ arrays

#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;
}

我被困在从二进制文件中读取数组。问题是打破阅读周期的条件甚至不起作用。程序一次又一次地读取相同的数组。

1 个答案:

答案 0 :(得分:0)

由于您使用!in.eof(),导致出现此类问题。解决这个问题的最简单方法之一就是像在这段代码中一样读取while循环内部

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;
 }

那么,这应该可以解决输出问题。