This compiles, but I cannot get to work

I'm having a hard time figuring this out. Just started programming and would appreciate some help/pointers on how to fix this. Thanks!


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
42
43
//Purpose:   This program reads floating point numbers until the end-of-file
//           while counting and summing the input data items.
//           After the while loop, it finds the average. 
//           Finally, display the counter, sum, and average. 

//include files...
#include <iostream>

using namespace std;

int main()
{
    //Variable declaration
    float number;       // storage for the number read   
    float average;
    float sum;
    int counter;

//Initialize variables
counter = 0;
sum = 0;

// loop until failed input data stream 
while ( cin )
{   
	cout <<"The number read is "<< number << endl; //don't change this line
	cin >> number; // process number and read the next number
	counter++;
	sum = sum + counter;
}

//Compute the average. Make sure there is no divide by zero.
if ( counter != 0)
	average = sum / counter;

//Display the results
    cout << endl;
    cout << "Number of input data items: " << counter << endl;
    cout << "Sum of input data items: " << sum << endl;
    cout << "Average of input data items: " << average << endl << endl;


This is the output I'm getting entering 1,2,3,4. There's some garbage being output before the actual number that I want to add.
The number read is -1.33754e-05
The number read is 1
The number read is 2
The number read is 3
The number read is 4

Number of input data items: 5
Sum of input data items: 15
Average of input data items: 3


I made a few tweaks to the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
counter = 0;
sum = 0;

//added this outside the while loop
cin >> number;

// loop until failed input data stream 
while ( cin )
{   
	cout <<"The number read is "<< number << endl; //don't change this line
	counter++;
	sum = sum + number; //not counter
	cin >> number; // process number and read the next number
}


This outputs
The number read is 1
The number read is 2
The number read is 3
The number read is 4

Number of input data items: 4
Sum of input data items: 10
Average of input data items: 2.5
Last edited on
1. Add this at the end:
1
2
	return 0;
}


2. what do you mean by this?:
// loop until failed input data stream

what exactly are you trying to read from?

At the moment, on line 27, your number variable is not initialized to anything and therefore contains garbage.

edit:
are you trying to do something like this:

1
2
3
4
5
6
7
std::fstream myfile("D:\\myDataFile.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        // do stuff with a
    }


?

OR, are you asking the user to enter a number on each iteration?
Last edited on
Topic archived. No new replies allowed.