简体   繁体   English

C ++:基于txt文件的Magic Square

[英]C++: Magic Square based on txt file

I am trying to create a Magic Square program based on a text file input. 我正在尝试基于文本文件输入创建Magic Square程序。 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. 我需要从'n'数字获取数组的大小,然后将行和列的值存储在2d数组中。 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. 3将是n,那么我需要一个2d数组来存储nxn信息。 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. 看来您还没有需要std::vector ,现在您可以使用简单的数组,实际上更难。

Creating a 1D array is this: 创建一维数组是这样的:

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

You can actually use this in place of 2D array. 您实际上可以用它代替2D数组。 You put row*n + column to access each element at row and col . 您将row*n + column放置在rowcol处以访问每个元素。 Or you can use a 2D array: 或者,您可以使用2D数组:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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