【问题标题】:Difference between CSV files which makes different outcome using getline()使用 getline() 产生不同结果的 CSV 文件之间的差异
【发布时间】:2020-05-14 13:07:29
【问题描述】:

我正在编写一个函数,它使用 getline() 读取 CSV 文件并将数据转换为向量的向量。为了测试它,我尝试读取两个具有相同分隔符的文件:一个从互联网导入,第二个从 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 的行则永远不会。我什至尝试删除 " 字符,但没有太大改进。但是从昏迷切换到 '\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;
}

【问题讨论】:

    标签: c++ csv


    【解决方案1】:

    问题出在这里:

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

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

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

    提示:为变量使用更有意义的名称。我没能完全理解你的逻辑,因为名为@9​​87654326@ 的变量以及rowline 同时存在让我头疼。

    【讨论】:

    • 看起来像“你不应该盲目地从互联网上复制代码”。非常感谢!
    • @Polonius 从不。 “它有效”没有任何意义,您总是需要了解它为什么有效。有时可以运行但您不知道为什么需要调试的代码比调试损坏的代码更困难
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多