Meo
Meo

Reputation: 160

Reading and merging specific columns from two different files

I'm trying to read specific lines in the third columns of two different files and merge them into a file with two columns. Specifically: I want to read line 9 – (17+2*139) from file 1 and line (17+2*139) – end from file 2. Below is the code that I wrote. It only outputs the result from the first file:

int main() {
    std::ifstream outfile_LD("outfile_LD.dat");
    std::ifstream outfile_LE("outfile_LE.dat");

    std::string line_LD;
    std::string line_LE;
    int count = 0;
    if (!outfile_LD || !outfile_LE) {
        std::cout << "Error opening file" <<
                     (outfile_LD? 2: 1) << ": " <<
                     strerror(errno) << "\n";
        return 1;
    }

    while (outfile_LD || outfile_LE)
    {
        count++;
        if (std::getline(outfile_LD, line_LD) && std::getline(outfile_LE, line_LE)) {
            if (count < 17 + 2*139) {
                if (count < 8) {
                    continue;
                } else {
                    double pedid_LE, lnlike_LE, log10like_LE;
                    outfile_LE >> pedid_LE >> lnlike_LE >> log10like_LE;
                    std::cout << log10like_LE << "\t";
                }
            } else {
                double pedid_LD, lnlike_LD, log10like_LD;
                outfile_LD >> pedid_LD >> lnlike_LD >> log10like_LD;
                std::cout << log10like_LD;
            }
        }
        std::cout << endl;
    }
    return 0;
}

Upvotes: 1

Views: 60

Answers (1)

TrueY
TrueY

Reputation: 7610

I assume the problem is in this line

if (std::getline(outfile_LD, line_LD) && std::getline(outfile_LE, line_LE))

When the first file is read through, it returns false. So the && will return false and you get a lot of NL when the second file is processed. Try to use || op.

But I would read the first file and then the second file in different loops. On the other hand I think it the 1st block outfile_LD should be read, then outfile_LE. In your code it seems to be mixed.

Upvotes: 1

Related Questions