This program is calculating and displaying the average of 3 groups of numbers in output file. Data is arranged in file so each group of numbers is preceded by number of data items in each group. It works for 2nd & 3rd group but calculation for 1st group is wrong. Thanks for your help!

//numbers.cpp                     
#include <iostream>
#include <fstream.h>
#include <stdlib.h>
using namespace std;
int main()
{
int numb, tot, count, sum;
float avg;

ifstream innumb;
ofstream outnumb;

innumb.open("innumb.txt");
outnumb.open("outnumb.txt");

 if (innumb.fail())
  {
     cout<<"Output file doesn't exist!";
     exit(1);
  }
   while (!innumb.eof())
     {
	innumb>>numb;
	count = numb;
      for (tot=0; tot<count; tot++)
       {
     innumb>>numb;
     sum = sum+ numb;
       }
     avg = sum/count;
     outnumb<<"The average of this group is: "<<avg<<endl;
	sum =0;
       avg=0;
    }
 system("PAUSE");
 return 0;
}  
//This is the run i get:  
//The average of this group is: 4.01863e+008  
//The average of this group is: 86
//The average of this group is: 75

<< moderator edit: added [code][/code] tags >>

Dani AI

Generated

The symptom you saw (one garbage average, then two sensible ones) is exactly what pointed out: sum was never initialized before the first group, so it contained an indeterminate value. After the first group the code sets sum = 0, so subsequent groups look fine. Local, automatic variables are not zeroed by the compiler — reading them before initialization is undefined behavior and produces the sporadic large number you saw.

A few practical improvements beyond initializing sum:

  • Initialize variables when you declare them and reinitialize per group (defensive coding).
  • Avoid while(!in.eof()); instead read the group count and check the stream: while (in >> count) { ... }. That prevents processing a partially-read final group.
  • Protect against count == 0 (divide-by-zero) and malformed files (check each in >> value for failure).
  • Use an appropriately large type for the accumulator (e.g., long long if many or large integers) to avoid overflow.
  • Do floating-point division explicitly: avg = static_cast<double>(sum) / count; so you don’t lose fractional data.
  • Check file opens with meaningful messages (don’t print “Output file doesn’t exist!” when you failed to open the input file), and avoid nonportable calls like system("PAUSE").

Example of a safer read/average pattern (modern headers, simple checks):

#include <fstream>
#include <iostream>

std::ifstream in("innumb.txt");
if (!in) { std::cerr << "Cannot open input file\n"; return 1; }

int count;
while (in >> count) {
    long long sum = 0;
    for (int i = 0; i < count; ++i) {
        int v;
        if (!(in >> v)) { std::cerr << "Unexpected EOF or bad data\n"; break; }
        sum += v;
    }
    double avg = count ? static_cast<double>(sum) / count : 0.0;
    std::cout << "Average: " << avg << '\n';
}

If you still see odd values after these fixes, run with tools that catch uninitialized reads (Valgrind or address/sanitizers) and add small diagnostic prints to confirm what was read at each step.

Recommended Answers

All 2 Replies

Change this:

int numb, tot, count, sum;

to this:

int numb, tot, count, sum = 0;

sum was uninitialized for the first run, but after the first run you set it to 0, so the second and third runs work properly.

commented: You Rock ;) +1

Thank you, it worked

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.