0

I'm trying to change this function to also account for when CSV files are given with \r endings. I can't seem to figure out how to get getline() take that into account.

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;

};
Will Luce
  • 1,781
  • 3
  • 20
  • 33

1 Answers1

0

This is a possible duplicate of Getting std :: ifstream to handle LF, CR, and CRLF?. The top answer is particularly good.

If you know every line ends with a \r you can always specify the getline delimiter with getline(input, data, '\r'), where input is an stream, data is a string, and the third parameter is the character to split by. You could also try something like the following after the start of the first while loop

// 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
Community
  • 1
  • 1
Daniel Robertson
  • 1,354
  • 13
  • 22