Re: Differences in reading from an istream vs. stringstream
David Crow <david_dot_crow@pbsnow.com> wrote:
Given the following input file:
bob 1 2 3 4 5
mary 2 3 4 5 6 7
susan 3 4 5 6 7 8 9
This code snippet does not read it correctly:
class Student
{
public:
...
private:
std::string _Name;
std::vector<int> _Grades;
};
...
/***** this only gets called once *****/
std::istream& operator>>(std::istream& is, Student& s)
{
string name = "";
is >> name;
std::vector<int> grades;
std::copy(std::istream_iterator<int>(is),
std::istream_iterator<int>(), std::back_inserter(grades));
/***** at this point, name and the grades vector are correct for
the 'first' line in the input file *****/
s.setName(name);
s.setGrades(grades);
return is;
}
...
std::ifstream fin;
std::vector<Student> students;
std::copy(std::istream_iterator<Student>(fin),
std::istream_iterator<Student>(), std::back_inserter(students));
/***** at this point, the students vector is empty *****/
Here's what happens. You seem to assume that std::copy inside operator>>
will stop at end-of-line. It does not. Instead, it reads 1, 2, 3, 4 and
5 successfully, but then it tries to read 'mary' and fails (because
'mary' cannot be read as an integer). So the stream is marked with
badbit, and that causes istream_iterator to report end-of-stream.
If I change operator>> to read from a stringstream instead, it works
as expected.
std::istream& operator>>(std::istream& is, Student& s)
{
std::string name = "";
is >> name;
std::string sGrades = "";
std::getline(is, sGrades);
But of course. getline does stop at end-of-line - that's the whole point
of the function after all.
So even though the one (and only) call to operator>> read the first
line of the file and assigned the values to the Student parameter,
the students vector got nothing added to it. Why would changing to a
stringstream fix this?
The difference is not between file stream and string stream. The
difference is between checking for or ignoring newline characters.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925