Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Reading Multiple Files

Reading Multiple Files


Video Summary: https://youtu.be/VmLTCphSj4k


Sometimes when you are reading files, you may want input from two different sources because the data was split up into multiple files. While you could read all of one file, close it, then open the second, it would be better to just read and alternate between both files. You can do this by opening two different ifstreams with two ifstream variables.

In this exercise, you will read five numbers counting up from two input files and output them in order to an output file. Start with the following code:


Notice the block while(!infile.eof()) . This is a loop that will read each input of the file one at a time "while" there is still text to read. You will learn more about it in later labs.

For this exercise:

  1. Make a txt file named "input1.txt" and write "0 2 4 6 8" in it
  2. Make a second txt file named "input2.txt" and write "1 3 5 7 9"
  3. Create an empty txt file named "output.txt"
  4. Create two ifstream variables, infile1 and infile2, and open the input txt files
  5. Create an ofstream variable output and open the txt file for it
  6. Create two int variables, one to store a number from each ifstream
  7. In the braces for while(!infile.eof()) , read one number into each into variable
  8. Output both numbers into the output file
  9. After the loop, close all the txt files

When you are finished, your output file should look like this:

0123456789

Solution