将std :: ifstream读取到行向量

Aus*_*yde 4 c++ file-io

我如何在每个行都是单个数字的文件中读取,然后将该数字输出到行向量中?

例如:file.txt包含:

314
159
265
123
456
Run Code Online (Sandbox Code Playgroud)

我试过这个实现:

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;
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试编译时,我会遇到如下错误:

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'
Run Code Online (Sandbox Code Playgroud)

所以,显然,出了点问题.有没有比我想要的更优雅的解决方案?(假设像Boost这样的第三方库不可用)

谢谢!

Tim*_*ter 20

我怀疑你想要这样的东西:

#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));
Run Code Online (Sandbox Code Playgroud)


Mar*_*ork 5

"Tim Sylvester"描述的标准迭代器是最好的答案.

但是,如果你想要一个手动循环,那么也
只是提供一个反例:'jamuraa'

vector<int> ifstream_lines(ifstream& fs)
{
    vector<int> out;
    int temp;

    while(fs >> temp)
    {
        // Loop only entered if the fs >> temp succeeded.
        // That means when you hit eof the loop is not entered.
        //
        // Why this works:
        // The result of the >> is an 'ifstream'. When an 'ifstream'
        // is used in a boolean context it is converted into a type
        // that is usable in a bool context by calling good() and returning
        // somthing that is equivalent to true if it works or somthing that 
        // is equivalent to false if it fails.
        //
        out.push_back(temp);
    }
    return out;
}
Run Code Online (Sandbox Code Playgroud)