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: 
Try:

```
#include <vector>
#include <fstream>
#include <iostream>

int main()
{
    std::ifstream   file("plop.dat");
    if(!file)
    {
        std::cerr << "Failed to open File\n";
        return 1;
    }

    // Keep looping until we are done.
    while(true)
    {
        int size;
        file >> size;

        // You said a size zero indicates termination.
        if (size == 0)
        {    break;
        }

        // Create a square 2D vector (Vector inside a Vector)
        std::vector<std::vector<int> >      matrix(size, std::vector<int>(size, 0));

        // Loop over each axis
        for(int x = 0;x < size; ++x)
        {
            for(int y = 0;y < size; ++y)
            {
                // Read one number for each location.
                // The operator >> automatically skips white space
                // White Space includes newline and tab. So it should work
                // perfectly if the input is OK. But it is hard to detect
                // an error in the format of the file.
                file >> matrix[x][y];
            }
        }
    }
}

```

~
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

```