I'm trying to write a function that reads values from a file and puts them in a matrix. The matrix (of two columns) is made by scanning the number of rows in the file and using that number as the number of rows in the matrix. To read the values, the ifstream object reader
is brought back to the start of the file. However, after doing so, reader
is stuck on an integer (I think it's a garbage value) for the entire loop. The function that dynamically allocates the matrix works fine.
I included the MCVE below.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(){
string fileChoice;
cout << "Choose a file to open: ";
cin >> fileChoice;
ifstream reader;
reader.open(fileChoice);
if (reader.fail()){
cerr << fileChoice << " could not be opened" << endl;
system("pause");
exit(1);
}
// https://stackoverflow.com/questions/26903919/c-allocate-dynamic-array-inside-a-function
int** Matrix = new int*[4];
for (int i = 0; i < 4; i++) {
Matrix[i] = new int[2];
}
reader.seekg(0, ios::beg);
for (int i = 0; i < 4; i++){
for (int j = 0; j < 2; j++){
reader >> Matrix[i][j];
cout << Matrix[i][j] << " ";
}
}
system("pause");
exit(0);
}
Here's the data in the sample file I used:
1 10
2 10
11 20
23 30
This is what I expected as output for cout
:
1 10 2 10 11 20 23 30
But this is what I got instead:
-842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451 -842150451
Additionally, when changing
reader.seekg(0, ios::beg);
for (int i = 0; i < 4; i++){
for (int j = 0; j < 2; j++){
reader >> Matrix[i][j];
cout << Matrix[i][j] << " ";
}
}
to
int beg;
reader.seekg(0, ios::beg);
for (int i = 0; i < 4; i++){
for (int j = 0; j < 2; j++){
reader >> beg;
cout << beg << " ";
}
}
I get the following output:
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460