string.find()无法打印出与该字符串匹配的所有行

时间:2016-05-11 02:08:46

标签: c++ string parsing csv vector

我正在使用向量来存储所有行(从CSV文件解析),它与我正在寻找的字符串匹配(通过string.find()!= string :: npos)。

但是,结果没有打印出包含该字符串的所有行。

CSV文件:

@api.multi
@api.onchange('seeddo_id','vehicle_id')
def onchange_vehicle(self):
    arrVehicle =[]
    print "test id"
    seed = self.seeddo_id.id

我想要的输出如下:

fruit, 1000, abc, d890, 1234
fruit, 1432, abc, d890, 1234
fruit, 8923, abc, d890, 1234
fruit, 1454, abc, d890, 1234
fruit, 2574, abc, d890, 1234
fruit, 1000, abc, d890, 1234
fruit, 1000, abc, d890, 1234
water, 1000, abc, d890, 1234
water, 1000, abc, pat1, 1432
water, 1000, abc, pat2, 8923
water, 1000, abc, pat3, 1454
water, 1000, abc, pat4, 2574
water, 1000, abc, d890, 1234

但是,实际输出是

fruit, 1432, abc, d890, 1234
fruit, 8923, abc, d890, 1234
fruit, 1454, abc, d890, 1234
fruit, 2574, abc, d890, 1234
water, 1000, abc, pat1, 1432
water, 1000, abc, pat2, 8923
water, 1000, abc, pat3, 1454
water, 1000, abc, pat4, 2574

代码如下:

water, 1000, abc, pat1, 1432
water, 1000, abc, pat2, 8923
water, 1000, abc, pat3, 1454
water, 1000, abc, pat4, 2574

1 个答案:

答案 0 :(得分:0)

这是一种更简单的方法,打印包含以下内容之一的行:
"1432", "8923", "1454", "2574"

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>

int main()
{
    std::ifstream file("file.txt");
    if (!file.is_open()) {
        std::cout << "Couldn't open file\n";
        return -1;
    }

    std::vector<std::string> find { "1432", "8923", "1454", "2574" };

    std::string line;
    while (std::getline(file, line)) {
        bool found = false;
        std::for_each(begin(find), end(find), [&](std::string s) {
            std::string::size_type n = 0;
            n = line.find(s);
            if (n != std::string::npos) {
                found = true;
                return;
            }
        });

        if (found)
            std::cout << line << '\n';
    }
}

打印预期结果:

fruit, 1432, abc, d890, 1234
fruit, 8923, abc, d890, 1234
fruit, 1454, abc, d890, 1234
fruit, 2574, abc, d890, 1234
water, 1000, abc, pat1, 1432
water, 1000, abc, pat2, 8923
water, 1000, abc, pat3, 1454
water, 1000, abc, pat4, 2574