将std :: ifstream读取到行向量

时间:2009-11-04 17:46:30

标签: c++ file-io

我如何阅读文件,其中每一行是一个数字,然后将该数字输出到一行中?

例如:file.txt包含:

314
159
265
123
456

我尝试过这个实现:

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;
}

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

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'
显然,有些事情是错误的。有没有比我想要的更优雅的解决方案? (假设像Boost这样的第三方库不可用)

谢谢!

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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;
}

答案 2 :(得分:1)

std::getline(stream, var)读入var的std :: string。我建议使用流操作符来读取int,并在需要时检查错误:

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