Question

I am new to c++. I am learning fast, but i dont know much yet.

I cannot see the problem with index in this 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);

     for (int i = 0; i < 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 help will be appreciated.

Was it helpful?

Solution 2

vector<string> rows;
               ^
             size() is 0
get_rows("ninja.txt", rows);

void get_rows(string filepath, vector<string> &rows) {
           //...
           int index = 0;
           rows[index] = str; // but there is no rows[0] yet
           //...
}

you should either use push_back to add new elements into vector or create a vector with specified size at the beginning (if it is known)

vector<string> rows(160);

which has advantage over the former as you can avoid potential reallocation (which may invalidate pointers to vector elements i.e)

OTHER TIPS

You have constructed an std::vector<string> object:

vector<string> rows;

and then later you are trying to access its elements although there are no elements in this vector yet:

rows[index] = str;

You should push new elements into the vector using push_back method:

rows.push_back(str);

Also note that using while (!file.eof()) is wrong becuase getline might fail inside the loop:

 while (!file.eof()) {
       getline(file, str);
       ...
 }

Your loop should look the following way:

 while (std::getline(file, str)) {
       if (str.empty()) continue;        // we skip empty lines
       rows.push_back(str);              // and push non-empty lines at the end
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top