问题描述
这里的人对你们来说是一个有趣的挑战。
我给了一个文本文件,我应该逐行处理信息。处理部分是微不足道的,只要我可以获得单独的行。但这里面临的挑战:
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:
- 我必须这么做,不要在我的代码中使用任何FOR / WHILE循环。 (这包括递归)
- 我只能使用标准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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!