逐行读取文件WITHOUT使用FOR / WHILE循环 [英] Reading file line by line WITHOUT using FOR/WHILE loop

查看:174
本文介绍了逐行读取文件WITHOUT使用FOR / WHILE循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的人对你们来说是一个有趣的挑战。
我给了一个文本文件,我应该逐行处理信息。处理部分是微不足道的,只要我可以获得单独的行。但这里面临的挑战:

Hey guys here's a interesting challenge for you all. I'm given a text file and I'm supposed to process the information line by line. The processing part is trivial so long as I can obtain the individual lines. However here's the challenge:


  1. 我必须这么做,不要在我的代码中使用任何FOR / WHILE循环。 (这包括递归)

  2. 我只能使用标准C ++库。

目前我最好的解决方案是:
是否有一个C ++迭代器可以逐行迭代文件?
但我希望一个更好的不涉及创建我自己的迭代器类或实现std :: string的代理。

Currently right now my best solution is this: Is there a C++ iterator that can iterate over a file line by line? but I'm hoping for a better one that does not involve creating my own iterator class or implementing a proxy for std::string.

PS这是一个学校任务,这里的挑战是使用std功能和算法的组合解决问题,但我不知道如何去解决它

P.S. this is for a school assignment and the challenge here was to solve the problem using a combination of std functionalities and algorithms but I have no clue how to go about solving it

推荐答案

ifstream input("somefile")

if (!input) { /* Handle error */ }

//MyDataType needs to implement an operator>>

std::vector<MyDataType> res;

std::istream_iterator<MyDataType> first(input);
std::istream_iterator<MyDataType> last;
std::copy(first,last, std::back_inserter(res));

//etc..

您的输入操作符可以是这样:

Your input operator can be something like this:

std::istream& operator>>(std::istream &in,MyDataType & out)
{
    std::string str;
    std::getline(in,str);
    //Do something with str without using loops
    return in;
}

这里有很多循环(你不想使用 goto ,不是吗?),但是它们都隐藏在 std :: copy std :: getline

There are a lot of loops here (you dont' want to use goto, don't you?), but they are all hidden behind std::copy and std::getline

这篇关于逐行读取文件WITHOUT使用FOR / WHILE循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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