I have an assignment where I am supposed to read multiple files containing integers (one on each line) and merge them into a output text file after sorting them. I am new to C++ so I do not know how everything works. I am testing my program with two .txt files. The first file is called fileone.txt, contains 1,2,7 (I do not know how to format this but they are all on different lines.) The second file is called filetwo.txt, and contains 1,3,5,9,10 (again every integer is on a different line).
I have written the following code which opens both files and prints the contents.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
ifstream iFile;
ifstream jFile;
iFile.open("fileone.txt");
jFile.open("filetwo.txt");
int int1 = 0;
int int2 = 0;
if (iFile.is_open() && jFile.is_open() ){
while (iFile.good() || jFile.good() ) {
iFile >> int1;
jFile >> int2;
cout << "From first file:" << int1 << endl;
cout << "From second file:" << int2 << endl;
}
}
iFile.close();
jFile.close();
return 0;
}
The output of this program is
The problem I am having is the last number in the first file gets printed multiple times. The output I want is to stop printing after printing the last integer from the file. The problem only appears when the second file contains more integers than the first one. Is there a way to stop printing from the first file when it reaches the end and while still print all the numbers from the second file?