function, files, and arrays

hi, I need help with my homework, but I am stuck on how to store data from a function using a .txt file into arrays. This is what I tried coding. What I need is to store text file into max, names[], my2DArr[][] so I can use them in other functions to finish up the homework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

void getData(ifstream &data, int &MAX, string names[], int my2DArr[][MAX]);

int main()
{
    int MAX;
    string names[MAX];
    int my2DArr[MAX][MAX];
    ifstream data;
    getData(data, MAX, names, my2DArr);

    return 0;
}

void getData(ifstream &data, int &MAX, string names[], int my2DArr[][MAX])
{
    data.open("club.txt", ios::in);
    data >> MAX;
    for (int i = 0; i < MAX; i++)
        data >> names[i];
    for (int i = 0; i < MAX; i++)
        for (int k = 0; k < MAX; k++)
            data >> my2DArr[i][k];
}


in the text file(example),
(max number of names)
(name)
(name)
(name)
001
010
100
Last edited on
Presumably this doesn't compile. Presumably your compiler is giving you errors, explaining why it doesn't compile. If you actually read those errors, you would see what the problem is.

Your compiler should be telling you that, inside the function getData, names and my2DArr are undefined. That's because you haven't defined any variables with those names within the scope of getData().

I assume you intended those to be the names of the arguments you're passing in?
also MAX - you gotta initialise MAX before using it.
since MAX is in the club.txt, I need to store it in MAX to initialize it? and how do i define names and my2Darr?
how do i define names and my2Darr?

You've already shown you know how to define the arguments to a function, because you've successfully done it for the first two arguments to getData(). Why are you not doing the same for the last two?
Last edited on
ok I fixed it, but I don't think it fixed my problem.
The error I get now is: use of parameter 'MAX' outside function body
Look at line 20:

void getData(ifstream &data, int &MAX, string names[], int my2DArr[][MAX])

Within the scope of that line, MAX is undefined. So you can't use it to define the size of my2Darr.

I'd just pass that in as an int**, if I were you.
I don't think we can do that because we just learn pointers(so we are not suppose to use these yet til next homework assignment) and we haven't learned about double pointers also.
Last edited on
Topic archived. No new replies allowed.