具有多个 EOL 字符的常规 CSV 解析器

General CSV Parser with multiple EOL characters

本文关键字:CSV 常规 字符 EOL      更新时间:2023-10-16

我正在尝试更改此功能,以考虑何时给出带有r结尾的 CSV 文件。我似乎不知道如何getline()考虑到这一点。

vector<vector<string>> Parse::parseCSV(string file)
{
    // input fstream instance
    ifstream inFile;
    inFile.open(file);
    // check for error
    if (inFile.fail()) { cerr << "Cannot open file" << endl; exit(1); }
    vector<vector<string>> data;
    string line;
    while (getline(inFile, line))
    {
        stringstream inputLine(line);
        char delimeter = ',';
        string word;
        vector<string> brokenLine;
        while (getline(inputLine, word, delimeter)) {
            word.erase(remove(word.begin(), word.end(), ' '), word.end());      // remove all white spaces
            brokenLine.push_back(word);
        }
        data.push_back(brokenLine);
    }
    inFile.close();
    return data;
};

这可能是 Get std :: ifstream 处理 LF、CR 和 CRLF 的副本?。最上面的答案特别好。

如果您知道每行都以r结尾,则始终可以使用 getline(input, data, 'r') 指定getline分隔符,其中输入是流,数据是字符串,第三个参数是要拆分的字符。您也可以在第一个 while 循环开始后尝试类似以下内容的操作

// after the start of the first while loop
stringstream inputLine;
size_t pos = line.find('r');
if(pos < line.size()) {
    inputLine << std::string(x.begin(), x.begin() + p);
    inputLine << "n"
    inputLine << std::string(x.begin() + p + 1, x.end());
} else {
    inputLine << line;
}
// the rest of your code here