this is my first time here. I'm learning C++ by myself from the book "Starting Out With C++" by Gaddis. Therefore I don't know who to ask, and then I found this website. Hope you don't mind to help me and I will learn a lot from you.
Here is one problem in the book:
Write a function named arrayToFile. The function should accept three arguments: the name of a le, a pointer to an int array, and the size of the array. The function should open the speci ed le in binary mode, write the contents of the array to the le, and then close the le. Write another function named fileToArray. This function should accept three arguments: the name of a le, a pointer to an int array, and the size of the array. The function should open the speci ed le in binary mode, read its contents into the array, and then close the le. Write a complete program that demonstrates these functions by using the arrayToFile function to write an array to a le, and then using the fileToArray function to read the data from the same le. After the data are read from the le into the array, display the array s contents on the screen.
And here is my code:
# include <iostream>
# include <string>
# include <fstream>
using namespace std;
const int SIZE = 10;
bool arrayToFile(fstream&, int*, int);
bool fileToArray(fstream&, int*, int);
int main()
{
int arr[SIZE] = { 10, 8, 9, 7, 6, 4, 5, 3, 2, 1 },
arrTest[SIZE];
fstream file;
if (arrayToFile(file, arr, SIZE))
{
if (fileToArray(file, arr, SIZE))
{
for (int n = 0; n < SIZE; n++)
{
cout << arrTest[n] << " ";
}
cout << endl;
return 0;
}
}
return 1;
}
bool fileToArray(fstream &file, int* a, int size)
{
file.open("t.dat", ios::in | ios::binary);
if (!file)
{
cout << "Can't open file t.dat\n";
return false;
}
file.read((char*)a, size);
file.close();
return true;
}
bool arrayToFile(fstream &file, int* a, int size)
{
file.open("t.dat", ios::out | ios::binary);
if (!file)
{
cout << "Can't open file t.dat\n";
return false;
}
file.write((char*)a, size);
file.close();
return true;
}
AND HERE IS THE OUTPUT: -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -85 8993460 -858993460 -858993460
I don't know what's wrong here, because the output is supposed to be like this: 10 8 9 7 6 4 5 3 2 1
Thanks for your help.