# Beginner Problem with Loop

• 10-10-2011
ToweyLeake
Beginner Problem with Loop
I wrote a program for an assignment that should read data from a file on the computer then display the sum of both the positive integers and negative integers. However, when I run my program it goes into an infinite loop. I need to understand what I am doing wrong. Any help would be greatly appreciated.

Code:

```#include <iostream> #include <fstream> using namespace std; int main() {     ifstream inputFile;     int even = 0;     int odd = 0;     int x;     inputFile.open("C:....\hw4dataf11.txt"); //I have attached the file to this post     if (!inputFile)         cout << "Error opening file.\n";     while(!inputFile.eof()){         if(x % 2 == 0){             even += x;             cout << "Number of even numbers is: " << even << endl;             even++;         }         else {             odd += x;             cout << "Number of odd numbers is: " << odd << endl;             odd++;         }     }     inputFile.close();     cout << "Program is finished. \n";Attachment 10981     return 0; }```
• 10-10-2011
Linell Bonnette
Where is the variable x coming from? You open the file and you go into a loop, but you don't actually read in x. Put a priming read (read in x) before the while loop and then read in another x at the end of the while loop.
• 10-11-2011
iMalc
This is a common problem, discussed in the FAQ on this site.
Cprogramming.com FAQ > Why it's bad to use feof() to control a loop

Hmm, that article is more about C though. Here's a discussion of the same problem in C++.
c++ - Reading from text file until EOF repeats last line - Stack Overflow
• 10-11-2011
ToweyLeake
Thank you both very much. I appreciate the help. ^_^
• 10-11-2011
ToweyLeake
Yes, that link did the trick!! Also, Linell, thank you for reminding me about the priming reads. You two really helped me out. ^_^