4
potatoes 1800
carrots 1300
beer 2500
tomato_sauce 500
The first line always has the number of items, and every next line has a single-word product, some spaces, and then the amount it costs. However, being a little eccentric, uncle Bob decided that he'd like to sort all his files, and that's where you come in.You've been given the task of writing a program that reads a file, sorts the contents, and then writes them back in a similar format. For simplicity, we'll use std::cin and std::cout for reading and writing, and we won't worry about how many spaces there are between the item name and the cost. We'll start by reading the number of items and printing it right back out:
#include <iostream>
int main() {
int num_items;
std::cin >> num_items;
std::cout << num_items << '\n';
}
Nothing new here. We'd also like to have a data structure to store the item name and cost in:
struct Item {
std::string name;
int cost;
};
We now know our program will look roughly like:
#include <iostream>
#include <string>
struct Item {
std::string name;
int cost;
};
int main() {
int num_items;
std::cin >> num_items;
// A: Where do we put the items?
for (int i = 0; i < num_items; ++i) {
Item item;
std::cin >> item.name;
std::cin >> item.cost;
// B: How do we store the item?
}
// C: How do we sort the items?
}
