Pregunta

I have a working function that reads lines from a text file (CSV), but I need to modify it to be able to read double quotes (I need to have these double quotes because some of my string values contain commas, so I am using double-quotes to denote the fact that the read function should ignore commas between the double-quotes). Is there a relatively simple way to modify the function below to accommodate the fact that some of the fields will be enclosed in double quotes?

A few other notes:

  1. I could have all of the fields enclosed in double-quotes fairly easily if that helps (rather than just the ones that are strings, as is currently the case)

  2. I could also change the delimiter fairly easily from a comma to some other character (like a pipe), but was hoping to stick with CSV if its easy to do so

Here is my current function:

void ReadLoanData(vector<ModelLoanData>& mLoan, int dealnum) {

// Variable declarations
fstream InputFile;
string CurFileName;
ostringstream s1;
string CurLineContents;
int LineCounter;
char * cstr;
vector<string> currow;
const char * delim = ",";

s1 << "ModelLoanData" << dealnum << ".csv";
CurFileName = s1.str();
InputFile.open(CurFileName, ios::in);

if (InputFile.is_open()) {

    LineCounter = 1;
    while (InputFile.good()) {
        // Grab the line
        while (getline (InputFile, CurLineContents)) {

            // Create a c-style string so we can tokenize
            cstr = new char [CurLineContents.length()+1];
            strcpy (cstr, CurLineContents.c_str());

            // Need to resolve the "blank" token issue (strtok vs. strsep)
            currow = split(cstr,delim);

            // Assign the values to our model loan data object
            mLoan[LineCounter] = AssignLoanData(currow);

            delete[] cstr;
            ++LineCounter;
        }   
    }
    // Close the input file
    InputFile.close();
}
else
    cout << "Error: File Did Not Open" << endl;

}

¿Fue útil?

Solución

The following works with the given input: a,b,c,"a,b,c","a,b",d,e,f

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    std::string line;
    while(std::getline(cin, line, '"')) {
        std::stringstream ss(line);
        while(std::getline(ss, line, ',')) {
            cout << line << endl;
        }
        if(std::getline(cin, line, '"')) {
            cout << line;
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top