Just wondering if anyone could comment on the layout of my code and how it is written. Obviously I'm still very much learning about the language and programming in general, so I'm aware that there may be other more effective ways to accomplish what I wanted, but I just wanted some feedback on the general user-friendliness of the code.
One thing I would say myself is that I could perhaps use more significant variable names, instead of abbreviations. Though in this situation, that's debatable.
The program basically is written to merge two files (containing whitespace-separated strings) together, maintaining the order of their strings.
For example:
File 1 - apple carrot
File 2 - banana durian
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
using std::cin; using std::cout;
using std::endl;
using std::ifstream; using std::ofstream;
using std::runtime_error;
using std::string;
int main()
try{
cout << "Enter the names of the files to be merged: " << endl;
cout << "File 1: " << endl;
string file1;
cin >> file1;
cout << "File 2: " << endl;
string file2;
cin >> file2;
// Always check input
ifstream ifs1(file1.c_str());
if(!ifs1) throw runtime_error("ERROR: Could not open file " + file1);
ifstream ifs2(file2.c_str());
if(!ifs2) throw runtime_error("ERROR: Could not open file " + file2);
cout << "Enter the destination file: " << endl;
string result;
cin >> result;
ofstream ofs(result.c_str());
if(!ofs) throw runtime_error("ERROR: Could not open output file " + result);
// We can never read an empty string from a file, so "" means we need to read
string s1 = "";
string s2 = "";
while(true){
if(s1 == "" && !(ifs1 >> s1)) break; // No more input from File1
if(s2 == "" && !(ifs2 >> s2)) break; // No more input from File2
if(s1 < s2){
ofs << s1 << " ";
s1 = "";
}
else{
ofs << s2 << " ";
s2 = "";
}
}
// Check if any input was left in the variables/not read
if(s1 != "") ofs << s1;
if(s2 != "") ofs << s2;
// In case one file is longer than the other
while(ifs1 >> s1) ofs << s1;
while(ifs2 >> s2) ofs << s2;
return 0;
}
catch(runtime_error e){
cout << e.what();
}