简体   繁体   中英

C++: Magic Square based on txt file

I am trying to create a Magic Square program based on a text file input. I'm getting stuck on the arrays. I need to get the size of the array from 'n' number then store the values of the rows and columns in 2d array. So here's an example from the text file:

3
4 9 2
3 5 7
8 1 6

3 would be the n, then I'd need a 2d array to store the nxn information. Here's what I coded:

int main() {
    int n;
    ifstream inFile;
    inFile.open("input.txt");
    inFile >> n;
    int square[n][n];

    readSquare(n, square);
}

void readSquare(int n, int square[][]) {
    ifstream inFile("input.txt");
    for (int r = 0; r < n; r++)
    {
        for (int c = 0; c < n; c++)
        {
            inFile >> square[r][c];
            cout << square[r][c];
            system("pause");
        }
    }
}

It looks like you haven't got to std::vector yet, for now you can just use plain arrays, which are actually harder.

Creating a 1D array is this:

int *square = new int[n*n];

You can actually use this in place of 2D array. You put row*n + column to access each element at row and col . Or you can use a 2D array:

int **square = new int*[n];
for (int i = 0; i < n; i++)
    square[i] = new int[n];

Then you have to pass the array by reference.

See also
Pass array by reference
Create 2D array

Putting it together:

void readSquare(int &n, int** &square)
{
    std::ifstream inFile("input.txt");
    if (!inFile)
        return;

    inFile >> n;
    if (n < 1) return;

    square = new int*[n];
    for (int i = 0; i < n; i++)
        square[i] = new int[n];

    int row = 0, col = 0;
    while (inFile)
    {
        int temp = 0;
        inFile >> temp;
        square[row][col] = temp;
        col++;
        if (col == n)
        {
            col = 0;
            row++;
            if (row == n) 
                break;
        }
    }
}

int main() 
{
    int n = 0;
    int **square = 0;
    readSquare(n, square);
    if (n)
    {
        //do stuff with n and square
        //free memory which was allocated by readSquare:
        for (int i = 0; i < n; i++)
            delete[]square[i];
        delete[]square;
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM