正在从多维数组的文本文件中读取常量变量

Reading const variables from a text file for multidimensional array

本文关键字:文件 读取 常量 变量 文本 数组      更新时间:2023-10-16

我是社区的新手,是一位同学推荐我来的。

我被困在一个学校项目上,希望得到一些指导,我不想有人帮我完成代码,我只想知道该怎么做…

当前的问题是创建一个多维数组,其中.txt文件的前两个数字就是数组的大小。

示例文本文件:

10 5
tom 91 67 84 50 69
suzy 74 78 58 62 64
Peter 55 95 81 77 61
Paul 91 95 92 77 86
Diane 91 54 52 53 92
Emily 82 71 66 68 95
Natalie 97 76 71 88 69
Ben 62 67 99 85 94
Mark 53 61 72 83 73
Anna 64 91 61 53 68

到目前为止,我已经从文本文件中读取了一个大小为2的数组,我将使用它作为我的数组大小。这就是我到目前为止所拥有的。

const int multiArraySize = 2;
void firstTwoNumbers(int numbers[]){
    int count = 0;             // Loop counter variable
    ifstream inputFile;        // Input file stream object
    // Open the file.
    inputFile.open("grades.txt");
    // Read the numbers from the file into the array.
    while (count < multiArraySize && inputFile >> numbers[count])
        count++;
    // Close the file.
    inputFile.close();
}

我主要有这个

int numbers[multiArraySize];
firstTwoNumbers(numbers);
int multiArray[numbers[0]][numbers[1]];

提前感谢您对Stack Overflow社区的帮助!

编辑:我已经成功读取了的前两个数字

我希望multiArray从数字数组继承其大小。

最好的方法是什么?我该怎么做?我读过一些关于const cast的文章,但我不知道这是否是一种正确的方法。

您需要为您的multiArray动态分配内存。动态二维数组是指向数组的指针数组。您应该使用一个循环来初始化它:

    int** multiArray = new int*[numbers[0]];
    for (int i =0; i <numbers[0]; i++)
        multiArray[i] = new int[numbers[1]];