12: Objects and Classes 2, I/O and Streams

General Information

Housekeeping

Announcements

See Announcements link in Canvas to keep up with what is going on. Here are a few for review:

Questions from last class or reading?

Homework Questions?

12.1: Cooperative Quizzes

Quiz Part 1: Individual Readiness Assessment

Quiz Part 2: Team Readiness Assessment (20m)

Quiz Appeals

12.2: Streams and Formatting

Reviewing Streams and Formatting

Output Streams

Input Streams

Output Formatting

Example Floating-Point Manipulators

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double number;
    cout << "Enter a number and I will format it: ";
    cin >> number;

    // Floating-point manipulators
    cout << "default:\t\t" << number << endl;
    cout << "scientific:\t\t" << scientific  << number << endl;
    cout << "fixed:\t\t\t" << fixed << number << endl;
    cout << "setprecision(3):\t" << setprecision(3) << number << endl;
    cout << "reset to default\n" << defaultfloat << setprecision(6);
    cout << "setprecision(3):\t" << setprecision(3) << number << endl;
    cout << "showpoint:\t\t" << showpoint << number << endl;

    return 0;
}

Example Text-Alignment Manipulators

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    string str;
    cout << "Enter a string and I will align it: ";
    getline(cin, str);

    // Text-alignment manipulators
    cout << "default:\t(" << str << ')' << endl;
    cout << "setw(7):\t(" << setw(7) << str << ')' << endl;
    cout << "setfill('*'):\t(" << setfill('*') << setw(7) << str << ')' << endl;
    cout << "left:\t\t(" << left << setw(7) << str << ')' << endl;
    cout << "right:\t\t(" << right << setw(7) << str << ')' << endl;
    cout << "reset to default\n" << right << setfill(' ');
    cout << "default:\t(" << str << ')' << endl;

    return 0;
}

Exercise 12.2: Coding Streams and Formatting (15m)

In this exercise we write code to neatly format output from a vector of objects.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    #include <iomanip>
    #include <vector>
    using namespace std;
    
    class Car {
        public:
        Car();
        Car(string newName, double newPrice, double newMpg);
        void print() const;
    
        private:
        string name;
        double price;
        int mpg;
    };
    
    Car::Car() {
        name = "none";
        price = 0.0;
        mpg = 0.0;
    }
    
    Car::Car(string newName, double newPrice, double newMpg) {
        name = newName;
        price = newPrice;
        mpg = newMpg;
    }
    
    void Car::print() const {
        cout << name << " @ " << price << " with MPG " << mpg << endl;
    }
    
    int main() {
        Car myCar("Tesla Model 3", 35000, 134);
        Car car2("Toyota Corolla", 25000, 34);
        Car car3("Junker", 250, 7);
        vector<Car> carList = { myCar, car2, car3 };
        for (unsigned i = 0; i < carList.size(); i++) {
            cout << (i + 1) << " ";
            carList.at(i).print();
        }
    
        return 0;
    }
    
  2. Compile your code to make sure it has correct syntax. Run the code and verify you see:
    1 Tesla Model 3 @ 35000 with MPG 134
    2 Toyota Corolla @ 25000 with MPG 34
    3 Junker @ 250 with MPG 7
    
  3. Inside the print() function, add the following formatting constants for the setw() function calls we add.
        // Formatting constants
        const int NAME_WIDTH = 18;
        const int PRICE_WIDTH = 10;
        const int MPG_WIDTH = 6;
    
  4. Now add statements to print() to format the output such that the name, price and mpg columns neatly align like:
    1 Tesla Model 3       35000.00   134
    2 Toyota Corolla      25000.00    34
    3 Junker                250.00     7
    

    Notice the left-alignment of names and the right alignment of numbers, including the way decimal points line up.

  5. Inside main(), add one or more statements to add a title to each column. When finished, the output looks like:
    # Name                   Price   MPG
    1 Tesla Model 3       35000.00   134
    2 Toyota Corolla      25000.00    34
    3 Junker                250.00     7
    
  6. Once satisfied with your code, copy your code into a text editor, save the file as "carlist.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

CA 12.2: Challenge activities

Any problems with any of these Challenge activities? (Zybooks sign in)

If so, list the CA numbers in Chat

12.3: Computer Files

About Computer Files

Types of Files

Translating to Unix Line Endings

Exercise 12.3: Preparing Text Files (5m)

In this exercise we upload or install a data file to work with in repl.it.

For this exercise we break into teams. Within the team, work with each other to solve any problems that occur.

Repli.it file tab

Specifications

  1. Start Repl.it and open or locate the Files tab, shown in the image to the right.

    You may need to sign up (free) and login to use the Files tab.

  2. Copy the contents of infile.txt to repl.it by either:

    We will read from this file after writing our program.

  3. Try running the translate program to remove "\r" from the file by typing the following command into the terminal window:
    tr -d "\r" < infile.txt > outfile.txt
    

    If successful, you will see another new file appear in the File tab named "outfile.txt".

12.4: Files and Streams

Reviewing Files and Streams

File stream: a data delivery path used to connect a program to a file.

Example Code (Repl.it)

/**
    Reads three numbers from the file infile.txt,
    sums the numbers, and writes the sum to the
    file outfile.txt.
*/
#include <iostream>
#include <fstream>   // for file I/O
#include <cstdlib>   // for exit()
using namespace std;

int main() {
    ifstream fin;
    fin.open("infile.txt");
    if (!fin.is_open()) {
        cout << "Input file failed to open.\n";
        exit(-1);
    }

    ofstream fout;
    fout.open("outfile.txt");
    if (!fout.is_open()) {
        cout << "Output file failed to open.\n";
        exit(-1);
    }

    int first, second, third;
    fin >> first >> second >> third;
    fout << "The sum of the first 3\n"
         << "numbers in infile.txt\n"
         << "is " << (first + second + third)
         << endl;

    fin.close();
    fout.close();

    cout << "Processing completed\n";

    return 0;
}

Streams, Objects and Errors

Commonly Used IO Stream Functions for Error Detection

Name Description
bad Returns true if a non-recoverable error has occurred on the stream.
eof Returns true if the stream has reached end-of-file.
fail Returns true if an error has occurred on the stream, including reaching the end of file.
good Returns true if the most recent I/O operation on the stream completed successfully.

12.4.2: Procedure For File I/O

  1. Place the following include directives in your program file:
    #include <fstream>   // for file I/O
    #include <iostream>  // for cout
    #include <cstdlib>   // for exit()
    using namespace std;
    
  2. Declare names for input and output streams like:
    ifstream fin;
    ofstream fout;
    
  3. Connect each stream to a file using open() and check for failure:
    fin.open("infile.txt");
    if (!fin.is_open()) {
        cout << "Input file failed to open.\n";
        exit(1);
    }
    
    fout.open("outfile.txt");
    if (!fout.is_open()) {
        cout << "Output file failed to open.\n";
        exit(1);
    }
    
  4. Read or write the data:
  5. Close the streams when finished reading and writing:
    fin.close();
    fout.close();
    

Exercise 12.4: Coding Files and Streams (10m)

In this exercise we write a program to read and write file data.

Remember to verify your code by compiling after each step.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Save the file infile.txt to the same folder as your program source code.

    We will read from this file after writing our program.

  3. Add the following include directives to your source code file:
    #include <fstream>   // for file I/O
    #include <cstdlib>   // for exit()
    
  4. Inside main(), declare names for the input and output streams:
    ifstream fin;
    ofstream fout;
    
  5. Add code to connect each stream to a file using open() and check for failure:
    fin.open("infile.txt");
    if (!fin.is_open()) {
        cout << "Input file failed to open.\n";
        exit(1);
    }
    
    fout.open("outfile.txt");
    if (!fout.is_open()) {
        cout << "Output file failed to open.\n";
        exit(2);
    }
    
  6. Add statements to read two numbers from the input stream. For example, here is possible code for reading the first number:
    int first;
    fin >> first;
    
  7. Add statements to write the two numbers to the output stream. For example, here is possible code for writing the first number:
    fout << "first = " << first << endl;
    
  8. Close the streams when finished reading and writing:
    fin.close();
    fout.close();
    
  9. At the end of main() before return 0, add a cout statement like:
    cout << "All done!\n";
    
  10. Compile and run your modified program to make sure you made the changes correctly.

    Notice that you do not see any output on the screen for file reading or writing. The output stream wrote the program output to an output file.

  11. View the content of outfile.txt, which should look like:
    first = 10
    second = 20
    
  12. Once satisfied with your code, copy your code into a text editor, save the file as "copytwo.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

12.5: Using Loops to Read Files

Reviewing Loops to Read Files

Commonly Used IO Stream Functions for Error Detection

Name Description
bad Returns true if a non-recoverable error has occurred on the stream.
eof Returns true if the stream has reached end-of-file.
fail Returns true if an error has occurred on the stream, including reaching the end of file.
good Returns true if the most recent I/O operation on the stream completed successfully.

Testing for End of File with Functions

Example Code Checking for Error (Repl.it)

#include <fstream>  // for file I/O
#include <iostream>
#include <cstdlib>  // for exit()
using namespace std;

int main() {
    ifstream fin;
    fin.open("rawdata.txt");
    if (!fin.is_open()) {
        cout << "Input file failed to open.\n";
        exit(-1);
    }

    double data, sum = 0;
    int count = 0;
    while (!fin.eof()) { // keep going until end of file
        fin >> data; // read the data
        if (!fin.bad() && !fin.eof()) { // is the data good?
            cout << "Read: " << data << endl;
            sum = sum + data;
            count++;
        }
    }
    cout << "average = " << (sum / count) << endl;
    fin.close();

    return 0;
}

Testing with the >> Operator

Example Code using Extraction Operator as Loop Test (Repl.it)

#include <fstream>  // for file I/O
#include <iostream>
#include <cstdlib>  // for exit()
using namespace std;

int main() {
    ifstream fin;
    fin.open("rawdata.txt");
    if (!fin.is_open()) {
        cout << "Input file failed to open.\n";
        exit(-1);
    }

    double data, sum = 0;
    int count = 0;
    while (fin >> data) {
        cout << "Read: " << data << endl;
        sum = sum + data;
        count++;
    }
    cout << "average = " << (sum / count) << endl;
    fin.close();

    return 0;
}

Using Loops with getline()

Example Program Reading a File Using getline() in a Loop

#include <fstream>   // for file I/O
#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    ifstream fin;
    fin.open("rawdata.txt");
    if (fin.fail()) {
        cout << "Input file failed to open.\n";
        exit(-1);
    }

    string line;
    int count = 1;
    while(getline(fin, line)) {
        cout << "Line " << count << ": " << line << endl;
        count++;
    }

    fin.close();

    return 0;
}

Exercise 12.5: Reading Files with Loops(12m)

In this exercise we explore the use of loops to read files.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    #include <fstream>   // for file I/O
    #include <cstdlib>   // for exit()
    using namespace std;
    
    int main() {
        // Enter code here
    
        return 0;
    }
    
  2. Save the file rawdata.txt to the same folder as your program source code.

    We will read from this file after writing our program.

  3. In main(), add code to declare an input stream named fin and to connect the stream to the input file "rawdata.txt". In addition, make sure you check for failure after calling open().

    For more information see the section Procedure For File I/O.

  4. First we read from the file using the following loop code:
    double nextNum;
    while (!fin.eof()) {
        fin >> nextNum;
        if (!fin.bad()) {
            cout << "Read: " << nextNum << endl;
        }
    }
    
  5. Add a statement after the above to close the input stream.
  6. Compile and run your code, then verify you see output like the following:
    Read: 12.34
    Read: -9.87654
    Read: 2.3131
    Read: -89.506
    Read: 12.3333
    Read: 92.8765
    Read: -123.457
    

    If you have problems, ask a classmate or the instructor for help as needed.

  7. Try adding a blank line at the end of rawdata.txt, and rerunning the program.

    Do you see any difference in output?

  8. Now change the loop code to read using the >> operator inside the test condition:
    while (fin >> nextNum) {
        cout << "Read: " << nextNum << endl;
    }
    
  9. Compile, run and verify you see the same output as before.
  10. Try adding and removing a blank line at the end of rawdata.txt, and rerunning the program.

    Do you see any difference in output? Add a comment to your code about which code technique seems superior.

    1. while (fin >> nextNum)
    2. while (!fin.eof()) {
          fin >> nextNum;
          if (!fin.bad()) {
             ...
          }
      
  11. Once satisfied with your code, copy your code into a text editor, save the file as "readwrite.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

12.6: Reading and Writing File Data with Vectors

Reading File Data into a Vector

Example Code (Repl.it)

#include <fstream>  // for file I/O
#include <iostream>
#include <vector>
#include <cstdlib>  // for exit()
using namespace std;

int main() {
    ifstream fin;
    fin.open("infile.txt");
    if (!fin.is_open()) {
        cout << "Input file failed to open.\n";
        exit(-1);
    }

    // Load data into a vector
    vector<int> data;
    int value;
    while(fin >> value) {
        cout << "Read: " << value << endl;
        data.push_back(value);
    }
    fin.close();

    // Process vector data
    double sum = 0;
    int count = data.size();
    for (int i = 0; i < count; i++) {
        sum = sum + data.at(i);
    }
    cout << "average = " << (sum / count) << endl;

    return 0;
}

Writing File Data from a Vector

Example Code (Repl.it)

#include <iostream>  // for cout
#include <iomanip>   // for setprecision
#include <fstream>   // for file I/O
#include <cstdlib>   // for exit()
#include <vector>
using namespace std;

void writeData(const vector<double>& data) {
    ofstream fout;
    fout.open("outfile.txt");
    if (!fout.is_open()) {
        cout << "Output file failed to open.\n";
        exit(-1);
    }
    fout << fixed << setprecision(2);
    for (unsigned i = 0; i < data.size(); i++) {
        fout << setw(10) << right << data.at(i) << endl;
    }
    fout.close();
}

int main() {
    // C++11 vector initializer list
    vector<double> data = { 12.94, -9.87654, 2.3131, -89.506, 12.9333,
        92.8765, -123.457, 42 };
    writeData(data);
    cout << "Done writing data to outfile.txt...\n";

    return 0;
}

Exercise 12.6: Reading and Writing File Data to and from a Vector (15m)

In this exercise we work with vectors while reading and writing data to files.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    #include <iomanip>   // for setprecision
    #include <fstream>   // for file I/O
    #include <cstdlib>   // for exit()
    #include <vector>
    using namespace std;
    
    void readData() {
        ifstream fin;
        fin.open("rawdata.txt");
        if (!fin.is_open()) {
            cout << "Input file failed to open.\n";
            exit(-1);
        }
        double nextNum;
        while (fin >> nextNum) {
            cout << "Read: " << nextNum << endl;
        }
        fin.close();
    }
    
    int main() {
        readData();
    
        return 0;
    }
    
  2. Save the file rawdata.txt to the same folder as your program source code.

    We will read from this file after writing our program.

  3. Inside the readData() function parenthesis, add the following parameter:
    void readData(vector<double>& data);
    
  4. In main() before the function call, declare a vector of type double named data. Then add the data variable as an argument to the readData() function like:
    readData(data);
    
  5. Inside the while-loop braces { }, add the following statement to save the values read from the input file into the vector.
    data.push_back(nextNum);
    
  6. In main() after the function call, add the following cout statement:
    cout << "Vector data:\n";
    
  7. After the above statement, add a for-loop to display all the elements of the vector.
    for (unsigned i  = 0; i < data.size(); i++) {
        cout << data.at(i) << endl;
    }
    
  8. Compile and run your code to verify it works correctly. When run, you should see the data from the file displayed twice like:
    Read: 12.94
    Read: -9.87654
    Read: 2.3131
    Read: -89.506
    Read: 12.3333
    Read: 92.8765
    Read: -123.457
    Vector data:
    12.34
    -9.87654
    2.3131
    -89.506
    12.3333
    92.8765
    -123.457
    
  9. Add a function with the following prototype to your code.
    void writeData(const vector<double>& data);
    
  10. Call the writeData() function from main() just before return 0.
  11. In writeData(), add code to declare an output stream named fout and to connect the stream to the output file "neat.txt". In addition, make sure you check for failure after calling open().
  12. After opening the output file, add the following code:
    fout << fixed << setprecision(2);
    for (unsigned i = 0; i < data.size(); i++) {
        fout << setw(10) << right << data.at(i) << endl;
    }
    
  13. Add a statement after the above to close the output stream.
  14. Compile and run your code to verify it works correctly. When run, you should see the following data in the file neat.txt:
         12.34
         -9.88
          2.31
        -89.51
         12.33
         92.88
       -123.46
    
  15. Once satisfied with your code, copy your code into a text editor, save the file as "vectorfile.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

12.7: Functions with Stream Parameters

Reviewing File Names as Strings

Example Using a string for File Names

#include <iostream>
#include <fstream>  // for file I/O
#include <cstdlib>  // for exit()
using namespace std;

void showFile(string filename) {
    string line;
    ifstream fin(filename);
    if (!fin.is_open()) {
        cout << "Input file " << filename << "failed to open.\n";
        exit(1);
    }
    // Read and display file contents
    while(getline(fin, line)) {
        cout << line << endl;
    }
    fin.close();
}

int main() {
    string filename, line;

    cout << "Enter a file name: ";
    cin >> filename;
    showFile(filename);

    return 0;
}

Functions with Stream Parameters

Example Using Stream Parameters (Repl.it)

#include <iostream>
#include <fstream>  // for file I/O
#include <cstdlib>  // for exit()
using namespace std;

/**
    Reads a line from the istream.

    @param aStream the output stream.
    @return The line of text read.
*/
string readLine(ifstream& aStream) {
    string line;
    getline(aStream, line);
    return line;
}

/**
    Writes a line to the ostream.

    @param aStream the output stream.
    @param line The string to output.
*/
void writeLine(ofstream& aStream, string line) {
    aStream << line << endl;
}

int main() {
    ifstream fin("infile.txt");
    if (!fin.is_open()) {
        cout << "Input file opening failed.\n";
        exit(-1);
    }

    ofstream fout("outfile.txt");
    if (!fout.is_open()) {
        cout << "Output file opening failed.\n";
        exit(-1);
    }

    while (fin.good()) {
        string line = readLine(fin);
        if (fin.good()) {
            writeLine(fout, line);
        }
    }

    fin.close();
    fout.close();
    cout << "Done copying file...\n";

    return 0;
}

Testing the Stream

Exercise 12.7: Coding Functions with Stream Parameters (15m)

In this exercise we explore passing an input stream to a function.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following code into the code editor.
    #include <iostream>
    #include <fstream>   // for file I/O
    #include <cstdlib>   // for exit()
    using namespace std;
    
    int main() {
        // Enter code here
    
        return 0;
    }
    
  2. Save the file products.txt to the same directory as your program source code.

    We will read from this file after writing our program.

  3. Write a function with the following signature:
    void readFile(string filename);
    
  4. Inside the function readFile(), add code to declare an input stream named fin and to connect the stream to the input file using the string fileName parameter. Make sure you connect the stream without calling open().
  5. Add the following code to function readFile() that reads all the values from the input file.
    while (fin.good()) {
        string name;
        double price;
        fin >> ws; // clear whitespace including newlines
        getline(fin, name);
        fin >> price;
        if (fin.good()) { // verify not end-of-file
            cout << name << " @ " << price << endl;
        }
    }
    
  6. Add a statement to close the input stream.
  7. In main(), call the readFile() function with:
    readFile("products.txt");
    
  8. Compile and run your code, then verify you see output like the following:
    Milk@3.95
    Bread@2.99
    Cheese@3.95
    
  9. Once satisfied with your code, copy your code into a text editor, save the file as "filelist.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

12.8: Reading and Writing File Data to and from a Vector of Objects

Reading File Data into a Vector of Objects

Example Reading a File into a Vector of Objects (Repl.it)

#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;

class Product {
public:
    Product();
    Product(string newName, double newPrice);
    void read(ifstream& fin);
    void print() const;
private:
    string name;
    double price;
};

Product::Product() {
    name = "Unknown";
    price = 0.0;
}

Product::Product(string newName, double newPrice) {
    name = newName;
    price = newPrice;
}

void Product::print() const {
    cout <<  name << " @ " << price << endl;
}

void Product::read(ifstream& fin) {
    fin >> ws; // clear whitespace including newlines
    getline(fin, name);
    fin >> price;
}

// Read from filename into the vector
void readFile(vector<Product>& list, string filename);

// Display vector data
void listProducts(const vector<Product>& list);

int main() {
    vector<Product> list;
    readFile(list, "products2.txt");

    cout << "\nProducts in my store:\n";
    listProducts(list);

    return 0;
}

void readFile(vector<Product>& list, string filename) {
    ifstream fin(filename.c_str());
    if (!fin.is_open()) {
        cout << "Input file failed to open.\n";
        exit(-1);
    }

    while(fin.good()) {
        Product temp;
        temp.read(fin);
        if (fin.good()) {
            list.push_back(temp);
        }
    }
    fin.close();
}

void listProducts(const vector<Product>& list) {
    for (unsigned i = 0; i < list.size(); i++) {
        Product temp = list.at(i);
        temp.print();
    }
}

Writing File Data from a Vector of Objects

Exercise 12.8: Read and Writing File Data to and from a Vector of Objects (20m)

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

In this exercise we explore reading a file into a vector of objects. Start with the following Product class.

#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;

class Product {
public:
    Product();
    Product(string newName, double newPrice);
    void print() const;
private:
    string name;
    double price;
};

Product::Product() {
    name = "none";
    price = 0.0;
}

Product::Product(string newName, double newPrice) {
    name = newName;
    price = newPrice;
}

void Product::print() const {
    cout <<  name << " @ " << price << endl;
}

// Read product data from a file.
void readFile(vector<Product>& list, string filename);

// List the products in the store.
void listProducts(const vector<Product>& store);

// Write vector of objects to the file.
void writeFile(vector<Product>& store, string fileName);

int main() {
    vector<Product> list;
    int choice;
    do { // simple menu
        cout << "\nSelect an option:\n";
        cout << "0. Exits program.\n";
        cout << "1. Load data from file.\n";
        cout << "2. Print data in vector.\n";
        cout << "3. Write data to a file.\n";
        cout << "Choice: ";
        cin >> choice;
        if (choice == 1) {
            // readFile(list, "products2.txt");
        } else if (choice == 2) {
            listProducts(list);
        } else if (choice == 3) {
            // writeFile(list, "saved.txt");
        } else if (choice != 0) {
            cout << "Please enter a number from 0 - 3.\n";
        }
    } while (choice != 0);
    cout << "Goodbye.\n";

    return 0;
}

void listProducts(const vector<Product>& list) {
    for (unsigned i = 0; i < list.size(); i++) {
        Product temp = list.at(i);
        temp.print();
    }
}

Specifications

  1. Start Repl.it and copy the above code into the code editor.
  2. Compile your code to make sure you copied it correctly.
  3. In the same directory (folder) as your source code, save the data file: products2.txt.
  4. In the Product class, add a read function with the following prototype:
    void read(ifstream& fin);
    
  5. Outside the Product class, add the implementation of the read function using the prototype just added.
    void Product::read(ifstream& fin) {
        // read the whitespace before getline
        // read the product name
        // read the price
    }
    
  6. Implement the readFile() function using the declared prototype from the starter code and the following pseudocode.
    void readFile(vector<Product>& list, string filename) {
        // open an input file stream
        // test if the stream failed to open
        // while the file stream is good
            // construct a temporary object
            // call the read() function on the object
            // if no error during read()
                // then push onto back of vector
        // close the stream after the loop ends
    }
    
  7. Call readFile() from main() by uncommenting the menu code like:
    readFile(list, "products2.txt");
    
  8. Compile and run your code to verify it works. When run, you should see the data from the file displayed like the following. Numbers in aqua italics show the input and are NOT part of the code to write.
    Select an option:
    0. Exist program.
    1. Load data from file.
    2. Print data in vector.
    3. Write data to a file.
    Choice: 1
    
    Select an option:
    0. Exist program.
    1. Load data from file.
    2. Print data in vector.
    3. Write data to a file.
    Choice: 2
    Milk @ 3.95
    Bread @ 2.99
    Cheese @ 3.95
    
    Select an option:
    0. Exist program.
    1. Load data from file.
    2. Print data in vector.
    3. Write data to a file.
    Choice: 4
    Please enter a number from 0 - 3.
    
    Select an option:
    0. Exist program.
    1. Load data from file.
    3. Write data to a file.
    Choice: 0
    Goodbye.
    
  9. After reading from a file works correctly, in the Product class, add a write function with the following prototype:
    void write(ofstream& fout);
    
  10. Outside the Product class, add the implementation of the write function using the prototype just added.
    void Product::write(ofstream& fout) {
        // write the product name
        // write the price
    }
    
  11. Implement the writeFile() function using the declared prototype from the starter code and the following pseudocode.
    void writeFile(vector<Product>& list, string filename) {
        // open an output file stream
        // test if the stream failed to open
        // for each object in the vector
            // call the write function
        // close the stream after the loop ends
    }
    

    Write an endl after each output command.

  12. Call writeFile() from main() by uncommenting the menu code like:
    writeFile(list, "saved.txt");
    
  13. Compile and run your code to verify it works as before. Select menu 3 to write to a file. Open the "saved.txt" output file and verify it is the same as the original "products2.txt" file.
  14. Once satisfied with your code, copy your code into a text editor, save the file as "productfile.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.