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

时间:2015-12-06 03:32:25

标签: c++ arrays

我正在尝试根据文本文件输入创建一个Magic Square程序。我被困在阵列上了。我需要从' n'中获取数组的大小。 number然后将行和列的值存储在2d数组中。 以下是文本文件中的一个示例:

3
4 9 2
3 5 7
8 1 6

3将是n,然后我需要一个2d数组来存储n x n信息。 这就是我编码的内容:

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

1 个答案:

答案 0 :(得分:0)

看起来你还没有std::vector,现在你可以使用普通数组,这实际上更难。

创建一维数组是这样的:

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

您实际上可以使用它来代替2D数组。您可以row*n + column访问rowcol的每个元素。或者你可以使用2D数组:

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

然后你必须通过引用传递数组。

另见
Pass array by reference
Create 2D array

把它放在一起:

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