繁体   English   中英

将std :: ifstream读取到行向量

[英]Reading an std::ifstream to a vector of lines

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

例如: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这样的第三方库不可用)

谢谢!

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

#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));

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

std::getline(stream, var)读入std::getline(stream, 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM