#include <iostream> //header files needed for the function and vector
#include <string>
#include <fstream>
using namespace std;
int main() // declaration of all variables
{
string line;
fstream chapter_one ("chapter1.txt"); //open the 3 text files
fstream chapter_two ("chapter2.txt");
fstream chapter_three ("chapter3.txt");
ofstream book ("book.txt"); //creates book.txt
if (chapter_one.is_open()) //if file chapter_one opens
{
while (! chapter_one.eof() ) //while NOT end of chapter1.txt
{
getline (chapter_one, line); //get contents of chapter1.txt
book << line << endl; //output contents of chapter1.txt to book.txt
}
while (! chapter_two.eof() ) //while NOT end of chapter2.txt
{
getline (chapter_two, line); //get contents of chapter2.txt
book << line << endl; //output contents of chapter2.txt to book.txt
}
while (! chapter_three.eof() ) //while NOT end of chapter3.txt
{
getline (chapter_three, line); //get contents of chapter3.txt
book << line << endl; //output contents of chapter3.txt to book.txt
}
cout <<"The files chapter1.txt, chapter2.txt and chapter3.txt. have all been joined\ntogether and outputted in the file book.txt.\n";
}
else cout <<"Unable to open file.\n"; //user error message
chapter_one.close();
chapter_two.close();
chapter_three.close();
book.close();
return 0;
}
Remember, each file can consist of any number of lines. So you must read and write each one entirely before the next. So, your algorithm must be something like:
open "book.txt" for create/write
for each input file name:
open the input file
for each line in the input file:
write it to the output file
close the input file