Coding style/layout - easy to read?

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

Output file - apple banana carrot durian

This is it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#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();
}
Last edited on
closed account (18hRX9L8)
It works!

But, the new file isnt formatted properly.
For example:

file1:
You
A
Lot


file2:
I
Like


file3:
YouALotILike


Should be like:
You
A
Lot
I
like


This actually is a problem for me, so if anyone who is more practiced can come and help. That would be nice.
Topic archived. No new replies allowed.