读取文件所需的 std::getline 的替代方案

Alternative to std::getline needed for reading a file

本文关键字:getline 方案 std 文件 读取      更新时间:2023-10-16

考虑以下方法,该方法从文本文件中读取一行并对其进行标记:

std::pair<int, int> METISParser::getHeader() {
    // handle header line
    int n;  // number of nodes
    int m;  // number of edges
    std::string line = "";
    assert (this->graphFile);
    if (std::getline(this->graphFile, line)) {
        std::vector<node> tokens = parseLine(line);
        n = tokens[0];
        m = tokens[1];
        return std::make_pair(n, m);
    } else {
        ERROR("getline not successful");
    }
}

std::getline发生崩溃(pointer being freed was not allocated - 此处不详细介绍)。如果我在其他系统上编译代码,则不会发生崩溃,并且很可能不是我自己的代码中的错误。目前我无法解决这个问题,也没有时间,所以我会在你的帮助下尝试绕过它:

你能建议一个不使用std::getline的替代实现吗?

编辑:我在Mac OS X 10.8与gcc-4.7.2上。我尝试使用gcc-4.7在SuSE Linux 12.2上,崩溃没有发生。

编辑:一种猜测是parseLine损坏了字符串。以下是完整性的代码:

static std::vector<node> parseLine(std::string line) {
    std::stringstream stream(line);
    std::string token;
    char delim = ' ';
    std::vector<node> adjacencies;
    // split string and push adjacent nodes
    while (std::getline(stream, token, delim)) {
        node v = atoi(token.c_str());
        adjacencies.push_back(v);
    }
    return adjacencies;
}

您可以随时编写自己的更慢更简单的getline,只是为了使其工作:

istream &diy_getline(istream &is, std::string &s, char delim = 'n')
{
    s.clear();
    int ch;
    while((ch = is.get()) != EOF && ch != delim)
        s.push_back(ch);
    return is;
]