std::vector subscript out of range while reading a file into the vector of strings in C++ -


i new c++. learning fast, dont know yet.

i cannot see problem index in function:

#include <iostream> #include <fstream> #include <string> #include <vector>  using namespace std;  void get_rows(string filepath, vector<string> &rows);  int main() {      vector<string> rows;      get_rows("ninja.txt", rows);       (int = 0; < rows.size(); i++) {           cout << rows[i] << endl;      } }  void get_rows(string filepath, vector<string> &rows) {       ifstream file;      file.open(filepath);       string str;      int index = 0;       while (!file.eof()) {             getline(file, str);            rows[index] = str;            index++;      } } 

any appreciated.

vector<string> rows;                ^              size() 0 get_rows("ninja.txt", rows);  void get_rows(string filepath, vector<string> &rows) {            //...            int index = 0;            rows[index] = str; // there no rows[0] yet            //... } 

you should either use push_back add new elements vector or create vector specified size @ beginning (if known)

vector<string> rows(160); 

which has advantage on former can avoid potential reallocation (which may invalidate pointers vector elements i.e)


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -