C ++ vector :: _ M_range_check Error?

Here is my function:

void loadfromfile(string fn, vector<string>& file){ int x = 0; ifstream text(fn.c_str()); while(text.good()){ getline(text, file.at(x)); x++; } //cout << fn << endl; } 

The fn value I pass in is just the name of the text file ("10a.txt") The value of the transferred file is declared as follows:

 vector<string> file1; 

The reason I didn’t determine the size is because I didn’t think I should have with vectors, they are dynamic ... right?

This function should read the given text file and store the full contents of each line in one vector cell.

Ex. Store the contents of the first line in file.at (0) Save the contents of the second line in file.at (1) And so on, until there are no more lines in the text file.

Mistake:

ending a call after calling an instance of 'std :: out_of_range' what (): vector :: _ M_range_check

I thought checking in a while loop should prevent this error!

Thanks in advance for your help.

+7
c ++ vector outofrangeexception
source share
2 answers

vector file empty, file.at(x) throw an exception out of range. You need std :: vector :: push_back here:

 std::string line; while(std::getline(text, line)) { file.push_back(line); } 

Or you could just build a line vector from a file:

 std::vector<std::string> lines((std::istream_iterator<std::string>(fn.c_str())), std::istream_iterator<std::string>()); 
+3
source share

file.at(x) refers to the element at the file.at(x) position, but it must exist, it is not automatically created if it is not. To add elements to your vector, you must use push_back or insert . For example:

 file.push_back(std::string()); // add a new blank string getline(text, file.back()); // get line and store it in the last element of the vector 
0
source share

All Articles