c++file-io

Reading an std::ifstream to a vector of lines


How would I go about reading in a file where each line is a single number, then outputing that number into a vector of lines?

eg: file.txt contains:

314
159
265
123
456

I have tried this implementation:

vector<int> ifstream_lines(ifstream& fs) {
    vector<int> out;
    int temp;
    getline(fs,temp);
    while (!fs.eof()) {
        out.push_back(temp);
        getline(fs,temp);
    }
    fs.seekg(0,ios::beg);
    fs.clear();
    return out;
}

but when I attempt to compile, I get errors such as:

error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline
(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : 
could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::ifstream'

so, obviously, something is wrong. Is there a more elegant solution than what I am trying? (Assuming 3rd party libraries like Boost are unavailable)

Thanks!


Solution

  • I suspect you want something like this:

    #include <vector>
    #include <fstream>
    #include <iterator>
    
    std::vector<int> out;
    
    std::ifstream fs("file.txt");
    
    std::copy(
        std::istream_iterator<int>(fs), 
        std::istream_iterator<int>(), 
        std::back_inserter(out));