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:
我传入的fn的值只是一个文本文件的名称('10a.txt'),我传入的文件的值声明如下:
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.
该函数应该读取给定的文本文件,并将每一行的全部内容存储到单个vector单元中。
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.
将第一行的内容存储到file.at(0)中,将第二行的内容存储到file.at(1)等,直到文本文件中没有更多的行。
The Error:
错误:
terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check
终止调用,在抛出std::out_of_range():什么():vector::_M_range_check。
I thought the check in the while loop should prevent this error!
我认为在while循环中检查应该可以防止这个错误!
Thanks in advance for your help.
谢谢你的帮助。
2 个解决方案
#1
3
vector file
is empty, file.at(x)
will throw out of range exception. You need std::vector::push_back here:
向量文件为空,文件。at(x)将抛出范围异常。你需要std::向量::push_back方法:
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>());
#2
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:
at(x)在x-th位置访问元素,但它必须存在,如果不存在,它不会自动创建。要向vector添加元素,必须使用push_back或insert。例如:
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
#1
3
vector file
is empty, file.at(x)
will throw out of range exception. You need std::vector::push_back here:
向量文件为空,文件。at(x)将抛出范围异常。你需要std::向量::push_back方法:
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>());
#2
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:
at(x)在x-th位置访问元素,但它必须存在,如果不存在,它不会自动创建。要向vector添加元素,必须使用push_back或insert。例如:
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