CSV文件之间的差异,使用getline()产生不同的结果
Difference between CSV files which makes different outcome using getline()
我正在编写一个函数,该函数使用 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
的变量以及同时存在row
和line
让我头晕目眩。
相关文章:
- 使用QProcess执行命令,并将结果存储在QStringList中
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- 使用++运算符会导致意外的结果
- 为什么在递归中使用循环会产生意想不到的结果?
- 警告 C4552:">>":未使用表达式的结果
- 在运行时使用范围更新结果
- 使用 find 解析文件会给出不同文件的奇怪结果
- c++ lambda:柯里和函数:使用按值捕获与按引用捕获返回不同的结果
- C++使用 g++ 时,没有结果,没有打印
- 使用不同的工具时,Eccodes 会产生不同的结果
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- 如何使用CPack打包多个cmake构建结果?
- 为什么这两段使用 constexpr、__PRETTY_FUNCTION__ 和 char * 的代码有不同的结果?
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- STD :: FPCLASSIFY的错误结果使用Valgrind进行长时间的双重双重结果
- (int)-2147483648的结果使用不同的编译器除以(int)-1
- 对 std::atomic::load 的结果使用结构取消引用 (->) 运算符是否安全
- 链接两个具有相同函数签名的强函数符号的结果使用 G++ 以及原因