为什么比较两个字符串的结果错过了最后匹配的字符串?

Why the results of comparing two string missed the last matched string?

我比较 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;
        }
    }
}

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