C++ vector::_M_range_check Error?
Asked Answered
B

2

13

Here's 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 value of fn that I'm passing in is just the name of a text file ('10a.txt') The value of file that I'm passing in is declared as follows:

vector<string> file1;

The reason I didn't define a size is because I didn't think I had to with vectors, they're dynamic... aren't they?

This function is supposed to read a given text file and store the full contents of each line into a single vector cell.

Ex. Store the contents of first line into file.at(0) Store the contents of the second line into file.at(1) And so on, until there aren't any more lines in the text file.

The Error:

terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check

I thought the check in the while loop should prevent this error!

Thanks in advance for your help.

Becka answered 13/9, 2013 at 23:37 Comment(1)
Duplicates and near-duplicates abound.Perishing
W
12

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

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

Or you could simply construct vector of string from file:

std::vector<std::string> lines((std::istream_iterator<std::string>(fn.c_str())),
                                std::istream_iterator<std::string>());
Whoop answered 13/9, 2013 at 23:40 Comment(0)
S
0

file.at(x) accesses the element at the x-th position, but this must exists, it is not automatically created if it is not present. 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
Shipboard answered 13/9, 2013 at 23:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.