Apr 16, 2012 at 9:14pm UTC
Writing code to read a .txt data file into a 2d array, and when it displays the array for some reason it does not include the first 2 elements of the data. I have no idea what to do I tried everything
the data file is:
1 78 15 10
2 45 35 67
3 103 75 19
4 30 30 30
5 98 14 47
6 76 57 54
7 110 34 76
8 20 58 14
9 11 76 27
10 60 34 99
11 89 11 76
12 10 36 34
13 27 33 86
14 69 35 45
15 79 74 16
16 12 24 98
17 97 53 54
18 74 12 97
19 36 85 58
20 26 44 46
the code is:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
// function declarations
void batch_scan(double x[][4],int rows, int cols);
ofstream outfile;
int main ()
{
int a,b, rows, cols;
double batchdata[20][4];
outfile.open("terrain.out");
ifstream infile;
infile.open("Batch_Options3.txt");
if (!infile )
{
cout<<"Error: Unable to open file"<<endl;
return 1;
}
else
{
infile>>rows>>cols;
for (a=0;a<=rows-1;a++) //reads in data for matrix from file
{
for (b=0;b<=cols-1;b++)
{
infile>>batchdata[a][b];
}
}
cout<<"The matrix is:\n\n";
outfile<<"The matrix is:\n\n";
for (a=0;a<=rows-1;a++) //prints out matrix
{
for (b=0;b<=cols-1;b++)
{
cout<<batchdata[a][b]<<" ";
outfile<<batchdata[a][b]<<" ";
}
cout<<endl;
outfile<<endl;
system("pause");
}
}
}
in conclusion, the numbers 1 and 78 do not appear in the array. It starts at 15 and includes everything up to the end at 46
Apr 16, 2012 at 9:23pm UTC
The first 2 values are being read in as your 'rows' and 'cols'.
It doesn't look like the file you're reading has the rows and columns listed in it, so you probably shouldn't be reading those from the file.
Apr 16, 2012 at 9:28pm UTC
Ok, I see what you mean, but how can I fix it? I have to use the given data file and can't edit it