将数值从二进制文件存储到数组中-C ++ [英] Storing numerical value from a binary file into an array- C++

查看:64
本文介绍了将数值从二进制文件存储到数组中-C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从包含100个双精度值的二进制文件中读取数值数据,并将其存储在名为myArray的数组中.当我打印myArray时,什么都没有显示,好像从未填充过myArray一样.感谢您的帮助.

I am trying to read numerical data from a binary file containing 100 double values and store it in an array called myArray. When I print myArray nothing is being shown, as if myArray has never been filled. Any help is appreciated.

int main() 
{
    int file_len; 
    ifstream infile; 
    infile.open("mybinfile.bin", ios::binary | ios::in); 
    if (!infile.is_open()) 
    {
    cout << "Error in opening the file. " << endl;
    }
    else
    {
        const int file_len = 100;

        std::vector<char> myVect;
        myVect.resize(file_len);

        int i = 0;
        infile.read((char *) (&temp), sizeof(char));
        myVect[i] = temp;
        while(!infile.eof())
        {

            myVect[i] = temp;
            i++;
            infile.read((char *)  (&temp), sizeof(char));
        }
        for (int i = 0; i < 100 ; i++)
        {cout << i << ": " << myVect[i]<< endl;}
    }    
    infile.close();

return 0;
} 

推荐答案

此处

infile.read((char*)&myArray, file_len * sizeof(double));

您将指针传递到指针进行翻倍.应该是

infile.read((char*)myArray, file_len * sizeof(double));

让我想知道为什么没有看到崩溃,因为写入随机存储器几乎永远不会失败.

Makes me wonder why you didn't see a crash, since writing into random memory almost never turns out well.

这篇关于将数值从二进制文件存储到数组中-C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆