title: Difference between while(!file.eof()) and while(file >> variable)
body: <p>First things first - I've got a text file in which there are binary numbers, one number for each row. I'm trying to read them and sum them up in a C++ program. I've written a function which transforms them to decimal and adds them after that and I know for sure that function's ok. And here's my problem - for these two different ways of reading a text file, I get different results (and only one of these results is right) [my function is decimal()]:</p>
  
  <pre><code>ifstream file;
  file.open("sample.txt");
  int sum = 0;
  string BinaryNumber;
  while (!file.eof()){
      file &gt;&gt; BinaryNumber;
      sum+=decimal(BinaryNumber);
  }
  </code></pre>
  
  <p>and that way my sum is too large, but by a small quantity.</p>
  
  <pre><code>ifstream file;
  file.open("sample.txt");
  int sum = 0;
  string BinaryNumber;
  while (file &gt;&gt; BinaryNumber){
      sum+=decimal(BinaryNumber);
  }
  </code></pre>
  
  <p>and this way gives me the the right sum. After some testing I came to a conclusion that the while loop with eof() is making one more iteration than the other while loop. So my question is - what is the difference between those two ways of reading from a text file? Why the first while loop gives me the wrong result and what may be this extra iteration that it's doing?</p>