CSV文件之间的差异,使用getline()产生不同的结果

Difference between CSV files which makes different outcome using getline()

本文关键字:结果 使用 之间 文件 CSV getline      更新时间:2023-10-16

我正在编写一个函数,该函数使用 getline(( 读取 CSV 文件并将数据转换为向量的向量。为了测试它,我尝试使用相同的分隔符读取两个文件:一个从 Internet 导入,另一个从 R 数据集导出。每个的前几行如下所示:

文件1.csv

User ID,Category 1,Category 2,Category 3,Category 4,Category 5,Category 6,Category 7,Category 8,Category 9,Category 10
User 1,0.93,1.8,2.29,0.62,0.8,2.42,3.19,2.79,1.82,2.42
User 2,1.02,2.2,2.66,0.64,1.42,3.18,3.21,2.63,1.86,2.32
User 3,1.22,0.8,0.54,0.53,0.24,1.54,3.18,2.8,1.31,2.5
User 4,0.45,1.8,0.29,0.57,0.46,1.52,3.18,2.96,1.57,2.86

文件2.csv

"","Sepal.Length","Sepal.Width","Petal.Length","Petal.Width"
"1",5.1,3.5,1.4,0.2
"2",4.9,3,1.4,0.2
"3",4.7,3.2,1.3,0.2
"4",4.6,3.1,1.5,0.2

然而,getline(( 只适用于第一个。在第二种情况下,它只是返回空格。即使我将单行从一个文件复制到另一个文件(当然添加或删除额外的列(,该函数的执行也类似——file1 中的行将始终被正确读取,而来自 file2 的行永远不会被正确读取。我什至尝试删除" chars,但没有太大改进。但是,从昏迷切换到"\t"可以解决问题。

我很好奇这两个文件之间有什么区别,导致如此不同的结果?

我的函数的源代码:

vector<vector<string>> readData(string fileName,int firstLine,char delimeter){
//Open data file
fstream fin;
fin.open(fileName, ios::in);
//Data stored in 2d vector of strings
vector<vector<string>> data;
vector<string> row;
string line,word,temp;
//Read data
int i=0;
while(fin>>temp){
row.clear();
//Read line and store in 'line'
getline(fin,line);
//Don't read first n lines
if (i<firstLine){
i++;
continue;
}
cout<<line<<endl;
//Break words
stringstream s(line);
//Read every column and store in in 'word;
while(getline(s,word,delimeter)){
row.push_back(word);
}
//Append row to the data vector
data.push_back(row);
}
//Close file
fin.close();
return data;
}

问题就在这里:

while(fin>>temp){
row.clear();
//Read line and store in 'line'
getline(fin,line);

fin >> temp读取所有内容,直到第一个空格或换行符。目前尚不清楚为什么这样做,因为只有getline(fin,line)您才尝试阅读整行并且您没有使用temp。在第一个文件中,fin>>temp仅使用"User",在第二个文件中,它使用整行,因为没有空格。

如果您查看第一个文件中的读取数据,您还会注意到每行的第一部分丢失了。

提示:为变量使用更有意义的名称。我没有设法完全理解你的逻辑,因为名为s的变量以及同时存在rowline让我头晕目眩。