C ++从文件中读取数据

时间:2018-05-07 20:05:26

标签: c++ readfile

假设我有一个包含此数据的.txt文件:

0:{start: 0, materialIndex: 0, count: 12}
1:{start: 12, materialIndex: 1, count: 12}
2:{start: 24, materialIndex: 0, count: 24}
3:{start: 48, materialIndex: 1, count: 12}
4:{start: 60, materialIndex: 0, count: 12}
...

27:{start: 378, materialIndex: 1, count: 6}

每件商品的ID都在它之前,价格在之后。 在我读完文件并且它有效之后,如果我想选择ID 2并显示它的价格乘以2,我该怎么办?

1 个答案:

答案 0 :(得分:1)

一种方法是将数据存储到std::vector

class Drink
{
    unsigned int id;
    std::string  name;
    double       price;
    friend std::istream& operator>>(std::istream& input, Drink& d);
};

std::istream& operator>>(std::istream& input, Drink& d)
{
    input >> d.id;
    input >> d.name;
    input >> d.price;
    return input;
}

您的输入代码如下:

std::ifstream drink_file("drinks.txt");
std::vector<Drink> database;
Drink d;
while (drink_file >> d)
{
    database.push_back(d);
}

您可以在database搜索ID == 2的饮料:

size_t quantity = database.size();
for (size_t index = 0; index < quantity; ++index)
{
    if (database[index].id == 2)
    {
       // Do something with record ID 2.
       break;
    }
}