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?
This is probably the root of your issue here. Does this statement evaluate true when you are at the end of either file or if you are not? Secondly, what if you're at the end of one file, but the other still has numbers remaining?
.eof() returns true when you actually reach the end of a file. So you want to continue reading while those two values return false therefore use the not (!) operator.
The problem you have currently is that both of the conditions in the while loop returns false && false because you just opened the file and you haven't reached the end of it, so the loop never executes.
Here's the problem with the 'while' condition. It can be helpful to evaluate each case individually.
When file1 is not at end of file, and file 2 is not at EOF, the codition evaluates thus:
while ( !false && !false ) = ( true && true ) = true
Now when file 1 has reached EOF and file 2 has not:
while (!true && !false ) = ( false && true ) = false
this is a very common logic error that even pros make from time to time. What you are trying to do is loop until you've reached the end of both files.. so you want to stop when eof() is true for both.
while ( !(inputFile1.eof() && inputFile2.eof()) )
There's still a big problem in your code after that one is fixed though. It'll get stuck in an endless loop, repeatedly writing '10' to the output file.