2

我有一个从文本文件(CSV)读取行的工作函数,但我需要修改它才能读取双引号(我需要这些双引号,因为我的一些字符串值包含逗号,所以我正在使用双引号表示读取函数应该忽略双引号之间的逗号)。是否有一种相对简单的方法来修改下面的函数以适应某些字段将用双引号括起来的事实?

其他一些注意事项:

  1. 如果有帮助,我可以很容易地将所有字段用双引号括起来(而不是像目前的情况那样只是字符串)

  2. 我也可以很容易地将分隔符从逗号更改为其他字符(如管道),但如果这样做很容易,我希望坚持使用 CSV

这是我当前的功能:

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;

}

4

1 回答 1

1

以下适用于给定的输入: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;
        }
    }
}
于 2013-07-25T14:16:36.197 回答