从多维数组的文本文件中读取const变量

时间:2015-07-05 21:27:08

标签: c++ arrays file-io multidimensional-array

我是社区的新手,并且是由同学提到的。

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

目前的问题是创建一个多维数组,其中.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的内容,但我不知道这是否是一种正确的方法......

1 个答案:

答案 0 :(得分:0)

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

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