简体   繁体   中英

Reading const variables from a text file for multidimensional array

I'm new to the community and was referred here by a fellow classmate.

I'm stuck on a school project and was hoping to get some guidance, I don't want someone to complete the code for me, I would just like an idea of what to do...

The question at hand is to create a multidimensional array where your first two numbers of a .txt file are the size of the array.

Example text file:

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

So far I have an array with the size of 2 reading from the text file, which I was going to use as my array size. This is what I have so far.

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

And in my main I have this

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

Thank you in advance for your help Stack Overflow Community!

EDIT: I have successfully read the first two numbers

I want multiArray to inherit its size from the numbers array.

What is the best way to do this? How would I go about this? I read somewhere about const cast, but I don't know if that is a proper way to go about it..

You need to dynamically allocate memory for your multiArray. A dynamic 2-dimensional array is an array of pointers to arrays. You should initialize it using a loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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