分裂矢量到矢量矢量

时间:2015-01-15 21:37:24

标签: c++ string vector split

我目前正在处理包含餐馆和其他一些信息的Yelp结果的文本文件。餐厅的每个元素由垂直线(|)分隔,每个餐厅由新线(\ n)分隔。 (见下面的例子)。我试图将这条线分成矢量矢量。较大的矢量将保持所有较小的矢量,而较小的矢量将各自保存其中一个餐馆的信息。我如何才能最好地接近这个?

以下是文件中的几行:

Meka's Lounge|42.74|-73.69|407 River Street+Troy, NY 12180|http ://www.yelp.com/biz/mekas-lounge-troy|Bars|5|2|4|4|3|4|5
Tosca Grille|42.73|-73.69|200 Broadway+Troy, NY 12180|http ://www.yelp.com/biz/tosca-grille-troy|American (New)|1|3|2|4
Happy Lunch|42.75|-73.68|827 River St+Troy, NY 12180|http ://www.yelp.com/biz/happy-lunch-troy|American (Traditional)|5|2
Hoosick Street Discount Beverage Center|42.74|-73.67|2200 19th St+Troy, NY 12180|http ://www.yelp.com/biz/hoosick-street-discount-beverage-center-troy|Beer, Wine & Spirits|4|5|5|5|5|4

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

std::vector< std::vector<std::string> > vecRestaurants;

std::ifstream in("restaurants.txt");
std::string line;

while (std::getline(in, line))
{
    std::vector<std::string> info;

    std::istringstream iss(line);
    while (std::getline(iss, line, '|'))
        info.push_back(line);

    vecRestaurants.push_back(info);
}

in.close();

// use vecRestaurants as needed...

话虽如此,假设每个餐厅的字段的含义和顺序始终相同,您也可以定义struct来保存单个字段,然后创建vector struct而不是1}}值,例如:

struct sRestaurantInfo
{
    std::string name;
    float field2; // ie 42.74, what is this?
    float field3; // ie -73.69, what is this?
    std::string address;
    std::string url;
    std::string type;
    // what are the remaining numbers?
};

std::vector<sRestaurantInfo> vecRestaurants;

std::ifstream in("restaurants.txt");
std::string line;

while (std::getline(in, line))
{
    sRestaurantInfo info;

    std::istringstream iss(line);
    std::getline(iss, info.name, '|');
    std::getline(iss, line, '|'); std::istringstream(line) >> info.field2;
    std::getline(iss, line, '|'); std::istringstream(line) >> info.field3;
    std::getline(iss, info.address, '|');
    std::getline(iss, info.url, '|');
    std::getline(iss, info.type, '|');
    // read the remaining numbers if needed...

    vecRestaurants.push_back(info);
}

in.close();

// use vecRestaurants as needed...