I have come up with code for this, but am currently having issues finalizing it. It seems that it only puts out some of the numbers in a numerical order, but not all from both text files. Any suggestions?
(1) get() doesn't get a number, and OP is using ints.
(2) Not a proper mergesort.
@kdog
I presume your input files are already sorted (in non-decreasing order)?
(1) initially, you must read a number from both files
(1a) Is it possible one or both files have no numbers?
(2) put the smaller number to the output file, and replace it, until there are no more numbers in the file to replace it
(3) output the remaining number to the output file, and repeat until there are no more numbers to replace it
You've done pretty good except for parts 1a and 3.
Lines 24-27: part 1a: You notice that the files are not usable. (I posit that an empty file is usable -- you just need to skip to step 3).
Line 41: part 3 is missing.
If your input files are not already sorted, then you need to just read the two files into a std::deque<int>, one after the other, std::sort() them, then write them to the output file.
@Duoas The files are already sorted, and i'm just trying to understand what you mean by your number 3. Would I just add two more if statements to continue reading the file? Like this?
@bobby
OP's question is textbook mergesort. I was kind enough to give you the benefit of the doubt with your code, which is currently less correct than OP's.
@kdog
That's the general idea, but remember that (for lines 1-2) you already output num1 (for lines 3-4: you already output num2) in the loop. You need to output the number that you have not yet output.
After that you need to output any numbers remaining in the still-good file.
while (both file A and file B have integers)
if (integer A < integer B)
output A
get next A
else
output B
get next B
if (A still has integers)
copy remaining integers from A to output
else
copy remaining integers from B to output
Remember that the trick is you have to attempt to read an integer to know if the file still has integers. (Which is what your code tries to do, so I think you've got that part okay.)
You are helping quite a bit @ Duoas, thank you greatly. I made a little progress, but still isn't the correct output. Sorry for being difficult. Here is the updated code.
For a homework, nothing, but for some I/O, where data is sent in chunks, it is very useful. It means you can call the function again on the same files to process new data as it comes.
Why not simply check to see if they opened or not?
Same difference, AFAIK. There is the potential that checking failbit can report errors unrelated to opening the file, but I am unaware of any implementation that actually does that.
take advantage of the bool operator
Again, same difference. Some people actually prefer to be explicit.