简体   繁体   中英

getline vs istream_iterator

如果您正在从文件进行逐行输入(将行读入字符串,以进行标记化),是否有理由优先使用 getline 或 istream_iterator 。

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::istream_iterator<Line>(std::cin),
                                       std::istream_iterator<Line>());
}

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, eg if you are expecting a well formed program and you expect to interpret it, it may be better to read in entire lines...)

@Martin York's answer-- while works-- fails in many areas when used with STL's algorithm. A simpler solution is to use inheritance.

struct line : public std::string{
    using std::string::string;
};

std::istream& operator>>(std::istream& s, line& l){
    std::getline(s, l);
    return s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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