-
More newbie questions
I have a problem with reading iofiles. I tried to create an array and output it to a file. Then input the array back into the program as variables.
But I am unable to get the correct values back.
Also, when I check the file, I realise only 1 value is written to the file.
What can/should I do?
Thanks in advance...
The codes is here:
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
int presskey();
int main()
{
int x, y, anarray[1][1];
cout << "Please enter a number. \n";
cin >> x;
cout << "Please enter another number. \n";
cin >> y;
ofstream a_file("arrayio.txt");
anarray[1][1] = x, y;
a_file << anarray[1][1];
a_file.close();
presskey();
ifstream b_file("arrayio.txt");
b_file >> anarray[1][1];
cout << anarray[1][1];
b_file.close();
presskey();
return 0;
}
int presskey()
{
cout << " Press Enter to continue... \n";
getch();
}
-
You are declaring an array of 1x1, and that can hold only one value. Try using :
int anarray[2];
anarray[0] = x;
anarray[1] = y;
-
Thanks for your answer. But how do I store and read a two demisional array from a file?
-
Try using write :
Code:
ofstream f("test.txt");
int arr[3][4];
f.write((char*)arr, sizeof(arr));
To read from the file use read :
Code:
ifstream inFile("test.txt");
int arr[3][4];
inFile.read((char*)arr, sizeof(arr));