I am pretty new to c++, and I am having some trouble trying to read a text file into a 2D array using dynamic memory allocation. I have been doing plenty of "googling" and research on how to do this, but nothing I've found is giving me the output I need when I print out the array. Any help would be greatly appreciated.
In case this is not enough information, my text file contains 2 matrices that need to be multiplied. I need to read these matrices into 2 different arrays that are dynamically allocated.
Unfortunately, my assignment requires a 2D array, I wish I could avoid it, but it doesn't look like I can.
Here is my source code:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin;
fin.open ("input1.txt");
int* a = NULL; // Pointer to int, initialize to nothing.
int n; // Size needed for array
fin >> n; // Read in the size
a = new int[n]; // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
a[i] = 0; // Initialize all elements to zero.
fin >> a[i];
cout << a[i] << endl;
}
This is the type of code that I found most when researching this. However, it is not even close to working .. the output I get is 3 and then 1 on another line.
My text file contains:
2 3
1 2 3
4 5 6
3 2
1 2
3 4
5 6
where the top lines are the number of rows and the number of columns ...
Your syntax is incorrect for a 2D array. The syntax should be int array[row_size][column_size]. You need to assign two values for the array.
int row, col;
fin >> row;
fin>> col;
int array[row][col];
That will give the correct size of the 2D array you are looking for. Your code is inputting 2 from the text file and setting that to the size of the one dimensional array. Then your code inputs the two values it reads in next from the file which is 3 and 1.
#include <cstdlib>
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream fin;
fin.open ("input1.txt");
if ( !fin ) exit( 1 );
int row1, col1; // Sizes needed for array
fin >> row1 >> col1;
int **a = newint *[row1];
for ( int i = 0; i < row1; i++ )
{
a[i] = newint[col1];
}
for ( int i = 0; i < row1; i++ )
{
for ( int j = 0; j < col1; j++ )
{
fin >> a[i][j];
}
}
// You do the same for the second array
return 0;
}