I have a problem for my CS class that I'm just not getting. I have to read an unspecified amount of integers in a text file. From there on I have to find the integers that are divisible by 5 and then add them up. Say I have a text file containing 1, 5, 7, 10, and 11, so my answer should be 15. The instructor says we have to use a while loop to read until End-Of-File.
Here is what I have, which is completely wrong:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int sum, even;
    sum = 0;
    ifstream inFile;
    inFile.open("numbers.txt");
    inFile >> even;
    do
    {
        if (even % 5 == 0)
        {
            sum = sum + even;
            cout << "\nThe sum of the numbers is:" << sum << endl;
        }
        else
        {
            cout << "\nNo numbers divisible by 5." << endl;
        }
    } 
    while (!inFile.eof());
    inFile.close();
    system("pause");
    return 0;
}
Something does happen; an endless loop that goes through large negative numbers.
Can anyone point me into the right direction?
Thanks,
Tobi
Update: I have this so far, but it prints out 4 answers.
#include <iostream> 
#include <fstream> 
using namespace std;
int main()
{
    int num, sum, count;
    sum = 0;
    ifstream inFile;
    inFile.open ("numbers2.txt");
    if (!inFile)
    {
        cout << "Can't open the input file.\n" << endl;
        system("pause");
        return 1;
     }
     inFile >> num;
     while (!inFile.eof())
     {
        inFile >> num;
        if (num % 5 == 0)
        {
            sum += num;
            cout << "Sum is: " << sum << endl;
        }
        else
        {
            cout << "Is not divisible by 5." << endl;
        }
     }
    inFile.close();
    system("pause");
    return 0;
}
My output looks like this:
- sum is: 5
- sum is: 25 (What I want as the output)
- Is not divisible by 5.
- Is not divisible by 5
I'll keep trying until I get this.
Thanks to everyone who has answered so far.
 
    


