Question: I am trying to read the unknown contents of a text file into a 2D array and have it come out looking like:

```
M [0] [0]=2 M [0] [1]=1 M [0] [2]=0
M [1] [0]=0 M [1] [1]=1 M [1] [2]=3
M [2] [0]=8 M [2] [1]=9 M [2] [2]=1
M [3] [0]=3 M [3] [1]=5 M [3] [2]=2

```

when the text file looks like this:

```
2
1 0
0 1
3
8 9 1
3 5 2
-2 3 -1
0

```

The zero at the end shows the end of the file.

My problem is the array can be a max size of 10X10 so there is no way of knowing what the size of the 2D array is and how to get it to look like i have shown above. 

Any ideas?

Answer: 
Just use 'fstream'. It ignores new lines and works just like 'iostream'. You just need to keep track of your matrix row and column.

```
//open "myFileName.txt" with an input file stream
std::ifstream inputFile("myFileName.txt");

while(!inputFile.eof()) //Check for end-of-file character
{
    //do this while keeping track of your matrix position
    inputFile >> M [curRow] [curColumn]
}

inputFile.close();

```

And don't forget to include the library:

```
#include <fstream>

```

Edit: The `>>` operator will also attempt to auto-cast the input as whatever type you are using:

```
double dTemp;
int iTemp;
std::string sTemp;

std::ifstream in("myFile.txt");

in >> dTemp; //input cast as double
in >> iTemp; //input cast as integer
in >> sTemp; //input cast as string

in.close();

```

Edit: Get the number of elements of the file

```
int temp, numberOfInputs;
while(!inputFile.eof())
{
    inputFile >> temp;
    ++numberOfInputs;
}

inputFile.seekg(0, std::ios::beg); //Go to beginning of file

```

Once you have the number of inputs you can use that to figure out the number of rows and colums.
Single and multi-dimensional C arrays are just contiguous pieces of memory. The difference is more syntactical in terms of what indexing into the array does: for a 2-dimensional array it just multiplies one dimension by the size of the other dimension before adding the second dimension to find the offset.

So to solve:

1. read the values into a std::vector (other answers have sugegsted ways to do this)
2. work out the size (integer square root of myArray.size())
3. calculate the index as, e.g.:

```
int idx(int size, int d1, int d2)
{
    return (d1*size)+d2;
}

```
4. Return the vector element at the index e.g.:

```
for (int d1 = 0; d1 < size; d1++)
{
    for (int d2 = 0; d2 < size; d2++)
        std::cout << "M [" << d1 << "] [" << d2 << "]=" << myArray[idx(size, d1, d2)] << " ";
    std::cout << std::endl;
}

```

gives me:

```
$ g++ arr.cpp && ./a.out
M[0][0]=2 M[0][1]=1 M[0][2]=0
M[1][0]=0 M[1][1]=1 M[1][2]=3
M[2][0]=8 M[2][1]=9 M[2][2]=1

```