Assignment 19
Due Tuesday, December 5 at 3:20pm on Canvas

Assignment 19.1: Barnyard Animals (10 pts)

  • In this assignment we write a program that copies five numbers from an input stream to an output stream.
  • Copy the following program into a C++ file, save it as animals.cpp, and then compile and run the starter program to make sure you copied it correctly.
    #include <iostream>
    using namespace std;
    int main() {
        // Enter your code here
        return 0;
  • Then, let's create a text file to test our program. Create a file in Notepad named infile.txt. and save it in the same directory as your project.
  • Note that if you are using CodeBlocks on the Mac, you will need to save your infile.txt in your users directory, which you can locate via the finder window by clicking the tab Go and selecting Home (Go->Home).
  • For other IDEs such as Xcode, you will need to research where to save your files using a Google search.
  • We will read from this file after writing our program.

  • Add the following new libraries that you need to your source code file:
    #include <fstream>   // for file I/O
    #include <cstdlib>   // for exit()
  • Inside main(), declare an input stream variable named fin and an output stream variable named fout.
  • Add code to connect each stream to a file using open() and check for failure:
  • Name your input and output files: infile.txt and outfile.txt respectively
  • 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;
  • Add 4 more pairs of statements like the ones above to read in the next 4 numbers.
  • Then, add an fout statement to print out a title at the top of your file
    fout << "Animals at our farm" << endl;
  • Next, write out the contents of your five variables to the file. For example:
fout << first << " chickens" << endl;
  • Add 4 more statements like the one above, so that your file contains the following when you are finished:
Animals at our farm
5 chickens
3 cows
8 ducks
2 horses
4 pigs
  • Close the streams when finished reading and writing:
  • Compile and run your program to make sure you made the changes correctly.
  • Notice that you do not see any output on the console screen. The output stream wrote the program output to the output file.
  • Open the output file you created and verify that your file contains the following:

    Animals at our farm
    5 chickens
    3 cows
    8 ducks
    2 horses
    4 pigs
  • Submit your program to Canvas when you are finished