Home > Software engineering >  Using data from 2D vector at runtime in C
Using data from 2D vector at runtime in C

Time:06-19

I have a function that takes the arguments of a 2D vector and writes the information from a file to that vector. But after I call the function and the data has been written to the vector, it acts as if the vector is empty, despite the vector being a accessible from anywhere in main. If do the printing within the load function it works just fine though.

This is my Load Function:

void LoadFile(vector<vector<string>> courseInfo) {

ifstream courses;
courses.open("CourseInfo.txt");

if (!courses.is_open()) {
    cout << "Error opening file";
}

if (courses) {
    string line;

    while (getline(courses, line)) {
        courseInfo.push_back(vector<string>());

        stringstream split(line);
        string value;

        while (getline(split, value, ',')) {
            courseInfo.back().push_back(value);
        }
    }
}

}

This is main:

int main(){

vector<vector<string>> courseInfo;
int choice = 0;
while (choice != 9) {
    cout << "Menu:" << endl;
    cout << "  1. Load Data Structure" << endl;
    cout << "  2. Print Course List" << endl;
    cout << "  3. Print Course" << endl;
    cout << "  9. Exit" << endl;
    cout << "What would you like to do? ";
    cin >> choice;

    switch (choice) {

    case 1:
        //load data
        LoadFile(courseInfo);
        break;

    case 2:
        //print course list

        for (int i = 0; i < courseInfo.size(); i  ) {
            for (int j = 0; j < courseInfo[i].size(); j  )
                std::cout << courseInfo[i][j] << ' ';

            std::cout << '\n';
        }
        break;

    case 3:
        //print course
        break;
    default:
        cout << choice << " Goodbye" << endl;

    }

}

}

If I try to print the information after loading it, nothing gets printed. I tried returning the vector with the function, but that made no difference.

CodePudding user response:

void LoadFile(vector<vector<string>> courseInfo) { ... }

This creates a copy of the vector because you pass it by value. You then store all the data in the copy and at the end of the function the copy is destroyed. At no point do you modify the original vector. Change it to

void LoadFile(vector<vector<string>> &courseInfo) { ... }
  • Related