You are reading from the stream to detect the number of colums and rows. Once that is done, the stream position is at the end of the file. To read the data in afterwards you must change the stream read position back to the begin of the file using
istream::seekg - C++ Reference[
^]:
fin.seekg(0);
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
{
fin >> arr[i * cols + j];
}
}
[EDIT]
There is also a logical error in your code. You want to calculate the sum for each column but you do not clear the
sum
value for the next one:
for(int j = 0; j < cols; j++)
{
int sum = 0;
for(int i = 0; i < rows; i++)
{
sum += arr[i * cols + j];
}
cout << "Sum for column " << j << " = " << sum << endl;
}
[/EDIT]
[EDIT2]
Calling
seekg()
is not enough. When the complete file has been read, the failbit is set and must be cleared before seeking:
fin.clear();
fin.seekg(0);
[EDIT2]