Code is Done Can You Just Explain My While loop? :D

Hello.
I failed my C++ class two semesters ago and I am retaking it. I am doing really well completing all my programming projects on time. I created this program last year in which it reads numbers from a file (of type double) and outputs its average. It runs great to my surprise. I just wanna know if anyone can explain my while loop? I just don't quite understand my Boolean expression. Please and Thank you. No Rush Its already submitted I just wished to be "schooled" lol.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# include <iostream>
# include <fstream>
# include <cstdlib>

int main()
{
    using namespace std;
    double sum = 0;
    int count = 0;
    double number;
    double average;
    ifstream list_num;

    //formula for average
    average = sum / count;
    //Opening file with list of numbers..
    list_num.open( "input.dat" );
    // See output if File fails to open.
    if ( list_num.fail() )
    {
        cout << "File Input.dat failed to open." << endl;
        exit(1);
    }
    // Calculatin average.
    while( list_num >> number )
    {
        count++;
        sum += number;
    }
     average = sum / count;
    //setting decimanl to 2 points
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    cout <<"Hello I'm here to tell you that \n " << endl;
    cout << "The averge of the numbers in file Input.dat is: \n " << endl;
    cout << average;
    cout << "\n\nEnd of program. \n \n Good-bye!" <<endl;
     list_num.close( );
}
Last edited on
It keeps looping until its the end of the file.
So as long as the list has a number it will keep looping?
that's the description of (list_num >> number)
So that means when the last number is read the loop stoops??????
Last edited on
I know I'm over analyzing Sorry but it has been bugging me.
I think I understand Thank you.
Yeah you got it :P Sorry for the late reply
Its ok I stay on this lol But thanks :)
Last edited on
If the next line in the file is not a double or EOF it keeps going.
If the next line is a new line it keeps going which surprised me. I guess it ignores the new line \n char.
So if it hits a Letter it stops.
It also surprised me that if the line is 10+20-10 , it still works and counts the last number as a negative, but 10+20/10 makes it stop at the /.
Topic archived. No new replies allowed.