writing array from external file
Dec 16, 2015 at 9:47pm UTC
Hello!
I'm trying to write a 2d array from data in an external file. I was trying to use a function to get it load line by line, but it didn't work, becuase the array stops loading after the first line.
Here's the content of the file:
1 29 38 94 50 67
37 899 10 119 121 138
11 15 203 401 222 109
2 94 55 5 35 21
And here's my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int getARRAY(int [][6], int , int );
void showARRAY(int [][6], int , int );
int main()
{
const int ROWS = 4;
const int COLUMNS = 6;
int numbers[ROWS][COLUMNS];
getARRAY(numbers, ROWS, COLUMNS);
cout << "\n\n\tSee files in C:\\ExternalFiles for output.\n\n\n" ;
showARRAY(numbers, ROWS, COLUMNS);
system("Pause" );
return 0;
}
int getARRAY(int numbers[][6], int ROWS, int COLUMNS)
{
fstream inputFile;
ofstream outputFile;
inputFile.open("C:\\ExternalFiles\\exfile2DARRAY.txt" );
if (inputFile.fail())
{
cerr << "\a\a**Error opening input file.\n" ;
exit(EXIT_FAILURE);
}
for (int x = 0; x < ROWS; x++)
{
for (int y = 0; y < 6; y++)
{
inputFile >> numbers[x][y];
cout << numbers[x][y] << " " ;
}
}
return numbers[4][6];
}
void showARRAY(int numbers[][6], int ROWS, int COLUMNS)
{
ofstream outputFile;
outputFile.open("C:\\ExternalFiles\\exfile2DARRAYout.txt" );
if (outputFile.fail())
{
cerr << "\a\a**Error opening output file.\n" ;
exit(EXIT_FAILURE);
}
outputFile << "Content of this array:\n\n" ;
for (int x = 0; x < ROWS; x++)
{
for (int y = 0; y < 6; y++)
{
outputFile << setw(4) << "[" << (x) << "][" << (y) << "]= " ;
outputFile << numbers[x][y];
}
outputFile.close();
}
}
What am I doing wrong? Does anyone have a good tutorial for working with 2d arrays and external files?
Topic archived. No new replies allowed.