Streams and input validation (part 1)

This lesson contains approximately 16 minutes of video content.

Reading from a stream

Examples of format read errors

Activity: Shopping list from file

Graded Autograder

Activity Prompt:

Suppose you are creating a program that makes it easier to read and load shopping lists to allow better shopping for groceries and necessities. You start with a simple grocery list with the columns as Item Name, Quantity, and Price. You want to read your shopping list file such that it reads those three columns and loads them into a vector of Items

struct Item { std::string itemName; int quantity; double price; };

You are given a file in the format

            Item Name 1 Quantity 1 Price 1
            Item Name 2 Quantity 2 Price 2
For example,
            Apples 10 5.99
            Tomatoes 5 3.99

Quantities are integers, and prices are doubles, so be very careful when reading and parsing those. Throw an exception when Quantity is not an integer or Price is not a double. Implement function LoadItemsToVector with the filename as the input in order to read the items from the file. After binding the file name to an input file stream, check whether the file is open. If it is not open, throw any exception. If the file is empty, return an empty vector.

Note: We are unable to provide you with "Run" functionality on this exercise. Therefore, we highly recommend that you work on this problem inside your CS 128 development environment and submit your solution code here to verify its correctness.

#include <vector> #include "item.hpp" std::vector<Item> LoadItemsToVector(std::string fileName);
#include "shoppinglist.hpp" #include <vector> std::vector<Item> LoadItemsToVector(std::string fileName) { std::vector<Item> items; // To implement return items; }
#include <string> struct Item { std::string itemName; int quantity; double price; };