【发布时间】:2017-12-27 18:16:57
【问题描述】:
我创建了一个程序,将数组保存到文件中,然后读取文件以在屏幕上显示数组。这是代码
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
int saveSize = 5;//size of the array
int save [saveSize + 1] = {saveSize, 7, 1, 2 ,3, 4}; //creating an array which first element is his own size
ofstream fileWrite; fileWrite.open ("File.dat", ios::out | ios::binary | ios::trunc);
fileWrite.write((char *) &save, sizeof(save)); //saves the array into the file
fileWrite.close();
int sizeLoad; //size of the array that will be loaded
ifstream fileRead; fileRead.open("File.dat", ios::in | ios::binary);
fileRead.read((char *) &sizeLoad, sizeof(int)); //it only reads the first element to know the size of the array
int load[sizeLoad+1]; //creating the array
fileRead.read((char *) &load, sizeof(int));
fileRead.close();
//showing the array
for(int i = 1; i <= sizeLoad; i++) cout << "Element " << i << ": " << load[i] << endl;
return 0;
}
问题是当我运行程序时,结果是这样的:
元素 1:2686224
元素 2:1878005308
元素 3:32
元素 4:2686232
元素 5:4199985
甚至没有接近。有人知道为什么会这样吗?
【问题讨论】:
-
int load[sizeLoad+1];之类的东西不是有效的 C++。不要使用数组,使用 std::vector。 -
您可能应该只使用
<<和>>来写入和读取文件,而不是将数组视为char*- 它更简单且不易出错。 -
请注意,
ofstream fileWrite; fileWrite.open (...);可以更简单地写成ofstream fileWrite(...);。这就是构造函数的用途。此外,ofstream的析构函数会关闭文件,因此不需要调用fileWrite.close()。fileRead也一样。