Mark S.
Mark S.

Reputation: 301

C++ vector::_M_range_check Error?

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.

Upvotes: 13

Views: 91160

Answers (2)

billz
billz

Reputation: 45410

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>());

Upvotes: 12

ChronoTrigger
ChronoTrigger

Reputation: 8617

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

Upvotes: 0

Related Questions