Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 654
Mark S. Avatar asked Sep 13 '13 23:09

Mark S.


1 Answers

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>());
like image 169
billz Avatar answered Sep 23 '22 13:09

billz