gpt4 book ai didi

c++ - 将二维数组写入/读取到二进制文件 C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:11:25 24 4
gpt4 key购买 nike

我正在尝试将二维数组中的数据写入二进制文件。我只写入值大于0的数据。因此,如果数据为0,则不会写入文件。数据如下:

Level       0   1   2   3   4   5

Row 0 4 3 1 0 2 4
Row 1 0 2 4 5 0 0
Row 2 3 2 1 5 2 0
Row 3 1 3 0 1 2 0

void {

// This is what i have for writing to file.

ofstream outBinFile;
ifstream inBinFile;
int row;
int column;

outBinFile.open("BINFILE.BIN", ios::out | ios::binary);

for (row = 0; row < MAX_ROW; row++){

for (column = 0; column < MAX_LEVEL; column++){

if (Array[row][column] != 0){

outBinFile.write (reinterpret_cast<char*> (&Array[row][column]), sizeof(int)
}
}
}

outBinFile.close();

// Reading to file.

inBinFile.open("BINFILE.BIN", ios::in | ios::binary);

for (row = 0; row < MAX_ROW; row++){

for (column = 0; column < MAX_LEVEL; column++){

if (Array[row][column] != 0){

inBinFile.read (reinterpret_cast<char*> (&Array[row][column]), sizeof(int)
}
}
}

inBinFile.close();
}

所有正在读取的数据都被插入到第一行,我如何在退出程序时加载数据?

最佳答案

只有当数据不等于 0 时才读取,这意味着它被第一个 0 锁定。一旦达到零,它就会停止读取。

在“if 命令”之前将文件读取到其他变量,然后在 if (variable != 0) Array[row][column] = variable 中。

如果你的数组是用数据初始化的,也许看看你的读数的设置位置。所以要设置 ok 我有零,接下来我应该从另一个位置读取。

关于c++ - 将二维数组写入/读取到二进制文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16002680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com