C++ vector::_M_range_check错误?

13

这是我的函数:

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;
}    
我传递的fn的值只是一个文本文件的名称(“10a.txt”)。 我传递的file的值声明如下:

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;

我之所以没有定义大小是因为我认为对于向量来说并不需要,它们是动态的……是吗?

这个函数应该读取给定的文本文件,并将每行的全部内容存储到一个单独的向量单元中。

例如,将第一行的内容存储在file.at(0)中, 将第二行的内容存储在file.at(1)中, 以此类推,直到文本文件中没有更多行。

错误信息:

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

我认为while循环中的检查应该可以防止这个错误!

提前感谢您的帮助。


重复问题(http://stackoverflow.com/q/6630663/179910)和(http://stackoverflow.com/q/18382135/179910),以及类似的重复问题(https://dev59.com/BnI_5IYBdhLWcg3wAeLl)随处可见(http://stackoverflow.com/q/10323187/179910)。 - Jerry Coffin
2个回答

12

向量file为空,使用file.at(x)将抛出范围异常。在这里需要使用std::vector::push_back

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

或者你可以直接从文件构建字符串向量:

std::vector<std::string> lines((std::istream_iterator<std::string>(fn.c_str())),
                                std::istream_iterator<std::string>());

0

file.at(x) 访问第 x 个位置的元素,但是该元素必须存在,如果不存在,则不会自动创建。要向您的向量添加元素,必须使用 push_backinsert。例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接