getline vs istream_iterator

2019-01-25 00:08发布

Should there be a reason to preffer either getline or istream_iterator if you are doing line by line input from a file(reading the line into a string, for tokenization).

2条回答
贼婆χ
2楼-- · 2019-01-25 00:34

I sometimes (depending on the situation) write a line class so I can use istream_iterator:

#include <string>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

struct Line
{
    std::string lineData;

    operator std::string() const
    {
        return lineData;
    }
};
std::istream& operator>>(std::istream& str,Line& data)
{
    std::getline(str,data.lineData);
    return str;
}

int main()
{
     std::vector<std::string>    lines;
     std::copy(std::istream_iterator<Line>(std::cin),
               std::istream_iterator<Line>(),
               std::back_inserter(lines)
              );
}
查看更多
狗以群分
3楼-- · 2019-01-25 00:49

getline will get you the entire line, whereas istream_iterator<std::string> will give you individual words (separated by whitespace).

Depends on what you are trying to accomplish, if you are asking which is better (tokenization is just one bit, e.g. if you are expecting a well formed program and you expect to interpret it, it may be better to read in entire lines...)

查看更多
登录 后发表回答