CS1440 – Lab (6)

March 21, 2001

You must complete this lab during the lab hour to receive full credit.

Phase (1):

Write a C++ code to read some integers in pairs from two different files.  The first number of each pair, x, is read from an input file called inpx.dat and the second number, y, is read from another file called inpy.dat.  Once you read the two numbers (a pair) take one of the following actions depending on their values:

1)  If both numbers are the same (x = y), write them one space apart into an output file called xyequal.out, and

2) If x is larger than y, write them one space apart into a file xlarger.out, and

3) If y is larger than x, write them one space apart into a file ylarger.out.

Your code reads numbers from both files until one or both of the files ran out of number.  In other words, you keep reading the numbers.  To check whether you are at the end of a file, you can use .eof( ) with your stream.  Thus, your while loop reads numbers from each file until it reaches the EOF in one of the files.

You need to create the two input files using the following data.

Here is the contents of the first file inpx.dat:

2 4 18 26 29 20 14 34 77 21 24 18 23 12 14 100

Here is the contents of the first file inpy.dat:

2 14 8 6 19 21 14 34 76 23 25 19 23 12 14 100

EOF : Stands for End Of File

Here are the 5 steps needed to read from/write to a file.

Step (1)- Include the fstream.h library, i.e. #include<fstream.h>.

Step (2)- Declare the input/output streams.

Step (3)- Connect to the input/out files through appropriate streams.

Step (4)- Read from/Write to the input/out files through appropriate streams.

Step (5)- Close the input/output files.

Phase (2)

Write a function that takes the values of x and y and returns, 0 if they are equal, returns the positive difference (x-y) if x > y, or return the negative difference (x - y) if x < y.  Then, based on the returned value, your code will determine to which file to write the x and y.

Write a function, void Read_value(ifstream& s, int& x, int& y), to do the reading x and y from an appropriate input file based on the stream that is passed to it as an argument, and another function, void Write_value(ofstream& s, int x, int y),  to do the writing of x and y to an appropriate file based on the stream that is passed to it.