0

I'm trying to read a file containing several variable length lists. Each list is on one line and I read it into a vector. But the last element on each line is getting stored into the vector twice.

I've coded it along the following lines:

ifstream file;
file.open("myfile.txt", ifstream::in);
string line;
while(!file.eof())
{
        getline(file, line);
        stringstream buffer(line);
        vector<int> temp;
        while (!buffer.eof())
        {
                buffer >> num;
                temp.push_back(num);
        }
        for(vector<int>::iterator i = temp.begin(); i != temp.end(); ++i)
                cout << *i << ' ';
}

Lines of input consist of tab separated integers. There is also a tab after the last element of each line. For a line like

1    3    4    2    

The expected output is

1 3 4 2

The output I'm getting is

1 3 4 2 2
Aakash Jain
  • 1,733
  • 16
  • 27
  • 2
    Where do people get taught `while (!file.eof())`? Genuine question. – juanchopanza May 31 '14 at 17:09
  • The internet, I guess. Is it wrong? What do you recommend instead? – Aakash Jain May 31 '14 at 17:11
  • Google the very title of your question... – Matteo Italia May 31 '14 at 17:12
  • Also: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – chris May 31 '14 at 17:17
  • 1
    By the way instead of looping to add elements to the vector you may want to do : `std::vector temp(std::istream_iterator(buffer), {});` – Veritas May 31 '14 at 17:22
  • 1
    @juanchopanza: It's the bad design of the I/O Streams library. And it shows you have important good naming is. `eof()` misleadingly reads as "is stream at end?", there's no denying in that. A longer and complicated name would be in order, something like `operation_encountered_eof()`. Unfortunately, we are left with the horrible naming and its consequences. – Christian Hackl May 31 '14 at 21:22

0 Answers0