我有一个从文本文件(CSV)读取行的工作函数,但我需要修改它才能读取双引号(我需要这些双引号,因为我的一些字符串值包含逗号,所以我使用双引号来表示read函数应该忽略双引号之间的逗号。是否有一种相对简单的方法来修改下面的函数以适应某些字段将用双引号括起来的事实?
其他几点说明:
如果有帮助的话,我可以很容易地用双引号括起所有字段(而不仅仅是字符串,就像目前的情况一样)
我也可以很容易地将逗号从逗号更改为其他角色(如管道),但如果容易这样做,我希望坚持使用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;
}
答案 0 :(得分: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;
}
}
}