读一个std :: ifstream到一个向量的行 [英] Reading an std::ifstream to a vector of lines

查看:236
本文介绍了读一个std :: ifstream到一个向量的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如:file.txt包含:

  314 
159
265
123
456 $ b b



我尝试过这个实现:

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

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

 错误C2784:'std :: basic_istream< _Elem,_Traits> & std :: getline 
(std :: basic_istream< _Elem,_Traits>&,std :: basic_string< _Elem,_Traits,_Alloc>&)':
无法推导' std :: basic_istream< _Elem,_Traits> &'from'std :: ifstream'

因此,显然有些错误。有比我所想的更优雅的解决方案吗? (假设第三方库不支持Boost)



谢谢!

解决方案

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

  #include< vector& 
#include< fstream>
#include
std :: vector< int>出口;

std :: ifstream fs(file.txt);

std :: copy(
std :: istream_iterator< int>(fs),
std :: istream_iterator< int>(),
std :: back_inserter (out));


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!

解决方案

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

这篇关于读一个std :: ifstream到一个向量的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆