c++ - C ++读入第一项,检查,然后读入其余项目
问题描述
我有一个看起来像这样的文件:
# Some comments
Some data
数据部分中的每一行将有 5 个项目。
我想逐行阅读文件,但忽略注释。为此,我想我需要检查第一项是否为#
. 但是,当我运行下面的代码时,会出现分段错误:
void readFile(string f, unordered_map<int, vector<double>> &l1, unordered_map<int, vector<double>> &l2,
unordered_map<int, vector<double>> &l3) {
ifstream file(f);
string first;
int second;
float third, fourth, fifth;
string line;
while(getline(file, line))
{
std::stringstream lineStream(line);
// Read an integer at a time from the line
lineStream >> first;
if (first == "#") { continue;}
else {
lineStream >> second >> third >> fourth >> fifth;
vector<double> location {third, fourth, fifth};
if (first == "sat") { l1[second].insert(l1[second].end(), location.begin(), location.end());
} else if (first == "user") {l2[second].insert(l2[second].end(), location.begin(), location.end());
} else {l3[second].insert(l3[second].end(), location.begin(), location.end());
}
cout << second << " " << third << " " << fourth << " " << fifth;
}
}
有谁知道为什么?
解决方案
您已将 lineStream 定义为字符串流。要使用提取运算符,您需要将其声明为 istringstream,以便您可以从中读取。
改变
std::stringstream lineStream(line);
至
std::istringstream lineStream(line);
推荐阅读
- java - 杰克逊确定列表字段的子类
- sql-server - 来自链接服务器的 SQL 数据查询
- cassandra - Cassandra 中的套接字连接数
- json - 无法在 swift 4.0 中将对象数组发布到 web api
- java - 当您必须替换许多片段状态时,保存片段状态的最佳实践方法是什么?
- reactjs - 反应useState钩子不更新状态onClick
- java - 如何使用 GregorianCalendar 在 Java 中获取当前周数和年份?
- android - android应用程序自动化的最佳方法
- css - 在反应中使用材料ui调用css类
- flutter - 我想把容器的一部分放在另一个容器上