Pradyot
Pradyot

Reputation: 3059

getline vs istream_iterator

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

Upvotes: 1

Views: 3849

Answers (3)

Jcsq6
Jcsq6

Reputation: 489

@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;
}

Upvotes: 1

Loki Astari
Loki Astari

Reputation: 264649

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

Upvotes: 15

dirkgently
dirkgently

Reputation: 111278

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

Upvotes: 6

Related Questions