Reading from File Contents to File / Outputting to a File


Hi,

I am struggling to get my program working.

The directions are to write a program that reads sorted integers from two separate files and merge the contents of the file to an output file (third file). The only standard output will be any errors to be reported and a
“FINISHED” statement after all items have been processed.

file1.txt
2
4
6
8
10

file2.txt
1
5
11
12
15

Output.txt
1
2
4
5
6
8
10
11
12
15


This is the code I have so far, but it is not working, and I have put the two txt files in the same directory as my .cpp file. It is not working though still. What have I done wrong and how can I fix it to read these integers from the two numbers and merge the contents into a third file?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

int num1;
int num2;

ifstream inputFile;
ifstream inputFile2;
inputFile.open ("file1.txt");
inputFile2.open("file2.txt");
ofstream outputFile;
outputFile.open("output.txt");

inputFile >> num1;
inputFile2 >> num2;

while(!inputFile.eof() && !inputFile2.eof())
{

if (num1 < num2)
{
outputFile << num1;
inputFile >> num1;
}
else
{       
outputFile << num2;
inputFile2 >> num2;
}

}

inputFile.close();
inputFile2.close();
outputFile.close();

return 0;
}
Last edited on
First off, add a 'endl' to the end of your output writes. Otherwise the output as is just looks like "12456810".

1
2
3
4
5
6
file1   file2
2       1
4       5
6       11
8       12
10      15


Look at your input carefully. The main problem with your algorithm is that it stops when one file is at eof() and not both. Going through sequentially, you can see that file 1 will reach it's end at 10 when there are still 3 values unread in file 2. But the program terminates since file 1 reached it's eof().

There are two main logical problems. The first is in your 'while' condition. The second has to do with the line:
if (num1 < num2)
Consider what that line will do once file1 has reached the end.

Last edited on
Topic archived. No new replies allowed.