【发布时间】:2022-02-03 18:15:11
【问题描述】:
我正在尝试读取 .CSV 文件,但在读取字符串时遇到错误。
就上下文而言,此 .CSV 文件包含一个人的姓名,后跟一些性格特征(例如,喜欢猫、巧克力、山脉等)。我想读入这些数据并将其存储在map<string, vector<string> > 中,其中人名是键,值是包含每个人格特征的向量。
我正在使用以下代码,但是当我取消注释 stringstream s(line); 行时,我收到此错误:
libc++abi: 以 std::length_error: basic_string 类型的未捕获异常终止
谁能告诉我这个错误是什么意思,我为什么会得到它,以及将来如何避免得到它?任何帮助表示赞赏c:
附:我还包括注释掉的其余功能,以便您可以看到成品应该做什么。这是我编写的一些示例数据:
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;
}
【问题讨论】:
标签: c++ string vector stringstream