# Example

In this section, we show a second example which involves reading data from a text file, processing the data, and finally displaying the result.

Example 2: Assume that the expenses of the last month have been logged in a text file. The file contains a list of products bought and how much was paid for each product. Note that the same product may appear several times in the file, e.g. pasta which was bough in two different occasions. The aim is to write a program that reads the list of expenses in the text file and displays the following:

• A list of products bought, sorted alphabetically by products name
• The total amount spent by product
• The total amount spent

An example of the text file and the program’s outut is shown below.

A possible strategy to solve this problem is to read all product expenses in the file into a vector and then sort the vector by products name. When producing the final output, the amount spent for each product needs to be aggregated, as the figure below suggests.

The C++ program listed below follows this idea. First, the type Product is defined. Two important functions are used to read the text file.

• Function read_product which reads one product’s data (i.e. name and amount spent) from the text file into a variable of type Product and then returns it. Note that the products name is separated from the amount paid by character '-'. Thus, std::getline(file, p.name, '-'); is used to read a product’s name until the separator character is reached.
• Function read_file reads all products from the text file and returns a vector with the list of products read. This functions calls function read_product to read separately each product.

In function display_aggregated_expenses_list, the loop in lines $121$ to $125$ aggregates (i.e. sums) the amount paid for a product p. Note that this loop is not execute for a product p, if p occurs only once in the file.