-3

Let's say I have a .txt file with this data in it:

1 Lipton 2  
2 CocaCola 2.5  
3 Pepsi 2

The ID for each item is before it and the price is after. After I read the file and it works, how should I do if I want to choose the ID 2 and display it's price multiplied by 2?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Niku Nik
  • 49
  • 1
  • 6

1 Answers1

1

One method is to store the data into a 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;
}

Your input code would like like this:

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

You could search the database for a drink with 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;
    }
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154