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).
Asked
Active
Viewed 3,703 times
1
-
2You've kind of answered the question yourself - use `getline` to get a line, or `istream_iterator` for tokenisation. – Mike Seymour Nov 13 '09 at 15:24
3 Answers
15
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>());
}

Martin York
- 257,169
- 86
- 333
- 562
6
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...)

dirkgently
- 108,024
- 16
- 131
- 187
-
Sorry I should have added that the line is comma seperated. so istream_iterator
would in fact fetch the entire line. – Pradyot Nov 13 '09 at 15:16 -
If you do no expect the input to be malformed _EVER_, which is a difficult thing to say, yes, you will get an entire line. – dirkgently Nov 13 '09 at 15:33
-
-
This is not entirely correct, you can use an overloaded getline to read up to the first user specified token (default is a newline) – rubenvb Jun 06 '10 at 16:45
0
@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;
}

Jcsq6
- 474
- 1
- 4
- 15