Search code examples
fstreamgetline

printing lines from files


I'm trying to print the first line from each file but I think its outputting the address instead.

#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

void FirstLineFromFile(ifstream files[], size_t count)
{
    const int BUFSIZE = 511;        
    char buf[BUFSIZE];

    ifstream *end, *start;

    for (start = files, end = files + count; start < end; start++)
    {
        cout << start->getline(buf, sizeof(buf)) << '\n';   
    }   
}

Solution

  • streams should not be passed by value. This code passes an array of streams by value. You can try to pass a vector instead and interate over them.

    void FirstLineFromFile(vector<ifstream*> files) {
        for (int i=0; i<files.size(); ++i) {
            string s;
            getline(*files[i], s);
            cout << s << endl;
        }
    }