首页 > 解决方案 > 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;
        }
    }

有谁知道为什么?

标签: c++

解决方案


您已将 lineStream 定义为字符串流。要使用提取运算符,您需要将其声明为 istringstream,以便您可以从中读取。

改变

std::stringstream lineStream(line);

std::istringstream lineStream(line);

推荐阅读