Thursday, 12 December 2019

C++ reading from file - last element gets read twice

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 temp;
while (!buffer.eof())
{
buffer >> num;

temp.push_back(num);
}
for(vector::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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...