stuck on program please help

Im stuck on this program. I'm trying to add my negative values and count them and get the average. when i print them i get 777. the input file i used had "51 144 5 16 8 0 -2 14 6 -4 173 263 11 9345 -135 777" i know my count should be 3 my sum -141 and my average should be -47.0.


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
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void get_data(int);

int main ()
{
  int list, i = 0;

  get_data(list);

  return 0;
}


void get_data(int list)
{
  string filename, filename2;
  ifstream infile;
  ofstream outfile;
  int count = 0, sum = 0, positive_num[30];
  double average = 0.0;

  cout << "Please enter the name of the input file." << endl; //prompt user for input file                                                                                
  cin >> filename;
  infile.open(filename.c_str());   //opens input file                                                                                                                     

  cout << "Please enter the name of the output file." << endl; //prompt user for output file                                                                              
  cin >> filename2;
  outfile.open(filename2.c_str()); //opens output file                                                                                                                    

  while(infile)
    {
      if(list < 0){
        count++;
        sum = sum + list;
      }
      else
        for(int index = 0; index<list; index++)
          {
            positive_num[index] = list;
          }
      infile >> list;
    }
  average = sum	/ count;

  infile >> list;
  outfile << "Kevin Hunt Section #1010 Assign #4" "\n\n";
  outfile << "Negative Values" "\n";
  outfile << "Count: " << count << "\n";
  outfile << "Sum: " << sum << "\n";
  outfile << "Average: " << average << "\n";
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int index = 0; // Note: you do not need this
  while(infile >> list)
    {
      if(list < 0){
        count++;
        sum = sum + list;
      }
      else
        for(int index = 0; index<list; index++) // This causes a crash
          {
            positive_num[index] = list; // Note: you do not need this
            index++ // Note: you do not need this
          }
      infile >> list;
    }
Note that index must not exceed 30.
Last edited on
thanks that worked however, its not reading in all my negative numbers.. its only reading -3 and -135 somehow its leaving the -4 out. the count is 2 and the sum is -137. do you have any idea what this could be?
I checked it and it worked as expected. Show your modified code please.
i had to remove the "infile >> list;" part. it works
Thanks
Topic archived. No new replies allowed.