简体   繁体   English

C++ 读入第一项,检查,然后读入 rest 项

[英]C++ read in first item of line, check, then read in rest of items

I have a file that looks like this:我有一个看起来像这样的文件:

# Some comments
Some data

Each line in the data section will have 5 items.数据部分中的每一行将有 5 个项目。

I would like to read in the file, line by line, but ignore the comments.我想逐行阅读文件,但忽略注释。 To do this, I think I would need to check if the first item is a # .为此,我想我需要检查第一项是否是# However, when I run the code below, I get a segmentation fault:但是,当我运行下面的代码时,会出现分段错误:

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;
        }
    }

Does anyone know why?有谁知道为什么?

You have lineStream delcared as a stringstream.您已将 lineStream 定义为字符串流。 To use the extraction operator you need to declare it as an istringstream so you can read from it.要使用提取运算符,您需要将其声明为 istringstream,以便您可以从中读取。

Change改变

std::stringstream lineStream(line);

to

std::istringstream lineStream(line);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM