It seems I don't understand completely reading from and into files, line by line.
Here is my code that is supposed to read lines of two file, into string variables, I assume, and then write them into third file:

line of first file
line of second file
.... so on
if one of files ends, the rest of the other is added to the end

Where is my mistakes? it compiled, but did not write anything into third file

    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;

    int main () {
        string name1, name2, line1, line2, name3;
        cin>>name1;
        cin>>name2;
        name3=name1+"."+name2;
        ifstream firstFile (name1.c_str());
        ifstream secondFile (name2.c_str());
        ofstream thirdFile (name3.c_str());
        while (!firstFile.fail() && !secondFile.fail()) {
            if (firstFile.eof()){
                getline (secondFile, line2);
                thirdFile<<line2<<endl;
            } else if (secondFile.eof()) {
                getline (firstFile, line1);
                thirdFile<<line1<<endl;
            } else {
                getline (firstFile, line1);
                getline (secondFile, line2);
                thirdFile<<line1<<endl<<line2<<endl;
            }
        }
        firstFile.close();
        secondFile.close();
        thirdFile.close();
        return 0;
    }

Recommended Answers

All 3 Replies

Where is my mistakes? it compiled, but did not write anything into third file

Interresting, it worked fine for me:

a.txt
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa

b.txt
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb
bbbbb

output:
run:
a.txt
b.txt
file
a.txt.b.txt
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb
aaaaa
bbbbb

What IDE are you using?

The way you have your code now if either stream fails it will end the loop. The problem is you arent doing anything after that. I would do this a little differently. Look at how this works.

while(getline(firstFile, line1) && getline(secondFile, line2))
{
    thirdFile<< line1 << endl << line2 << endl;
}
if(firstFile.fail() && !secondFile.fail())  // if first file ended first
{
    while(getline(secondFile, line2))
    {
        thirdFile<< line2 << endl;
    }
}
if(!firstFile.fail() && secondFile.fail()) // if second file ended first
{
    while(getline(firstFile, line1))
    {
        thirdFile<< line1 << endl;
    }
}

Andrew, I was submitting it in codeLab (I'm using my work computer now which does not have any). I'll try it when get home (Dev-C++).
Nathan, it makes so much more sense now, thanks! CodeLab still does not accept though..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.