【问题标题】:C++: Magic Square based on txt fileC++:基于txt文件的魔方
【发布时间】:2015-12-06 03:32:24
【问题描述】:

我正在尝试基于文本文件输入创建一个Magic Square 程序。我被困在阵列上。我需要从'n'数字中获取数组的大小,然后将行和列的值存储在二维数组中。 下面是文本文件中的一个示例:

3
4 9 2
3 5 7
8 1 6

3 将是 n,然后我需要一个二维数组来存储 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");
        }
    }
}

【问题讨论】:

  • 你这样做是为了学习 C++,还是为了获得一个工作程序?
  • 你不能定义这样的数组(非常量大小),你不能将多维数组作为参数传递。您应该改用std::vector&lt;std::vector&lt;int&gt;&gt;
  • @Beta 我这样做是为了完成家庭作业。所以我猜是“学习 C++”。
  • @JonathanPotter 是二维向量吗?我需要创建多个函数,我需要根据说明传递一些 2D 的东西
  • 所以我认为std::vector是被禁止的。我建议你先尝试一些简单的事情:一个使用数组(可变长度)的动态分配的程序,以及一个接受int* 类型参数的函数。一旦完美运行,您就可以考虑二维数组了。

标签: c++ arrays


【解决方案1】:

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

创建一维数组是这样的:

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

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

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

【讨论】:

  • 嗨。我很感激你的回答。但是您能解释一下**&amp; 标志背后的含义吗?
  • &amp; 在 C++ 中做了不同的事情。在上述函数中,它用于指示参数正在“通过引用传递”。这意味着对nsquare 的更改将被保留。 * 是类似于数组的指针。而** 是指向指针的指针,类似于“数组数组”或二维数组。这在 c++ 中很重要,你必须阅读有关它的书籍,我无法在评论部分进行更多解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多