【问题标题】:Why the results of comparing two string missed the last matched string?为什么比较两个字符串的结果错过了最后一个匹配的字符串?
【发布时间】:2016-08-29 06:54:43
【问题描述】:

我比较了 csv 文件中的两个字符串。 由于解析csv文件的结果是得到逗号分隔的数据行。

编码工作正常,但无法显示最后匹配的行。

CSV 文件内容:

Title,sn,sn,sn
test,123,344,222
test,123,344,222
test,123,344,222
test,123,344,222
test,456,677,223
test,5,4545,32
apple,23,44,22
apple,323,23,22

例如,我的代码只显示了缺少最后匹配行的内容,

Title,sn,sn,sn
test,123,344,222
test,123,344,222
test,123,344,222
test,123,344,222
test,456,677,223

而不是,

Title,sn,sn,sn
test,123,344,222
test,123,344,222
test,123,344,222
test,123,344,222
test,456,677,223
test,5,4545,32

代码如下:

int main()
{
    string line;
    ifstream file("sample.csv");

    if(!file)
    {
        cout << "Error, could not open file." << endl;
        return -1;
    }
    while(getline(file, line))
    {
        stringstream ss(line);
        string line2;

        getline(file, line2, ',');

        string str = "test";
        if(line2 == str)
        {
            cout << line << endl;
        }
    }
}

【问题讨论】:

    标签: c++ string csv compare getline


    【解决方案1】:

    每个循环,你都会得到一条线,以及它之后的线。当循环到达最后一行时,它后面没有一行,因此与“test”的比较永远不会正确,因为您已经在查看最后一行。如果您将第二个 getline 更改为 getline(ss, line2, ',');,那么现在您只会在每个循环中查看一行,因为您从 ss 而不是文件中提取每一行的第一部分(但第一行带有 Title,sn,sn,sn被跳过。)要跳过检查第一行(如果该行是标题),您可以在循环之前添加一个额外的getline(file, line);

    【讨论】:

    • 非常感谢,@10101 =)
    猜你喜欢
    • 1970-01-01
    • 2015-07-31
    • 2022-03-30
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多