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;
}
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: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:
to print all elements that actually are in the vector. Or check its size before: