Indexing a 2D vector is crashing my program

342 views Asked by At

I'm taking input from a txt file and storing it in a 2D vector. That part works fine. My program seems to error out as soon as I try and access individual elements of the 2D vector. From what I've searched, I'm indexing the vector the correct way, so does anyone know why this would crash my code?

edit: I am accessing the vector correctly. getInput2D() is actually failing to append temp_vec to output_vector. What would be the correct syntax then be to dynamically create a 2D vector in this situation?

#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <vector.>
#include <cmath>

using namespace std;

vector<vector<string>> output_vector{};

void getInput2D() { 
    
    ifstream file("C:\\Users\\ImTheUser\\Documents\\input.txt");
    string line;
    vector<string> temp_vec;
    
    if (file.is_open()) { 
        while (getline(file, line)) {
            if (line[0] != ' ') {
                temp_vec.push_back(line);
                temp_vec.clear();
            }

            else {
                output_vector.push_back(temp_vec);
                temp_vec.clear();
            }
        }
    }
    file.close();
}

int main() {
    
    getInput2D();
    cout << output_vector[0][0] << endl;
    return 0;
}
1

There are 1 answers

2
463035818_is_not_an_ai On

I'm indexing the vector the correct way, so does anyone know why this would crash my code?

Assuming you are absolutely certain that output_vector has 1 or more elements and that its first element has 1 or more elements, this is the correct way to access them:

cout << output_vector[0][0] << endl;

However, as you are reading from an external ressource (a file), you cannot be absolutely certain that the vector has any elements at all and you should not rely on such assumptions. Instead use either a loop:

for (const auto& lines : output_vector) {
    for (const auto& line : lines) {
        std::cout << line << '\n';
    }
}

to print all elements that actually are in the vector. Or check its size before:

if (output_vector.size() > 0 && output_vector[0].size() > 0) {
     std::cout << output_vector[0][0];
} else {
     std::cout << "error. output_vector is empty\n";
}