libc++abi: terminating with uncaught exception of type std::length_error: basic_string

libc++abi: terminating with uncaught exception of type std::length_error: basic_string

我正在尝试读取 .CSV 文件,但在读取字符串时遇到错误。

对于上下文,此 .CSV 文件包含一个人名,后跟一些性格特征(例如,喜欢猫、巧克力、山脉等)。我想读取此数据并将其存储在 map<string, vector<string> > 中,其中人名是键,值是包含每个人格特征的向量。

我正在使用以下代码,但当我取消注释行 stringstream s(line); 时,我收到此错误:

libc++abi:终止并出现 std::length_error 类型的未捕获异常:basic_string

任何人都可以告诉我这个错误是什么意思,为什么我会收到它,以及如何避免将来收到它?感谢任何帮助 c:

P.S。我还包括了注释掉的其余功能,这样您就可以看到成品应该做什么。这是我制作的一些示例数据:

John,Dog,DC,Beach,Hamburgers,Brownies
Sue,Cat,DC,Beach,Hot Dogs,Brownies
Jim,Dog,Marvel,Mountains,Hot Dogs,Cupcakes

它应该存储为:

[John] = {Dog, DC, Beach, Hamburgers, Brownies}
[Sue]  = {Cat, DC, Beach, Hot Dogs, Brownies}
[Jim]  = {Dog, Marvel, Mountains, Hot Dogs, Cupcakes}
//specialized function for reading files
//stores the values in the file in a map with the participant's name as the key and a vector of
//strings as the value
map<string, vector<string> > readFile(fstream & f) {
    map<string, vector<string> > output;

    //variables for use in splitting the values stored in the .csv
    vector<string> row;
    string word, line;

    //reading the file
    while (!f.eof()) {
        row.clear();

        //reading the next line in the file
        getline(f, line);

        //removing the trailing newline character
        line.pop_back();

        //creating new string stream object using line
        //stringstream s(line);

/*
        //separating the contents of a line by commas and storing them in row
        while (getline(s, word, ',')) {
            row.push_back(word);
        }

        //removing the name from the beginning of the vector and storing it in a
        //separate variable
        string name = row[0];
        row.erase(row.begin());

        //adding new entry to output
        output[name] = row;
*/
    }

    return output;
}

这里的问题是 f.eof()getline 失败之前不会 return 为真。当getline读取文件最后一行时,getline成功,文件定位在最后一个字节之后,但f.eof还没有设置。因此,您在 zero-length 字符串上调用 line.pop_back()

相反,使用这个成语:

    while( getline(f, line) )
    {
        row.clear()
        ...