Posted by: nepali8 April 21, 2011
IT -- Solutions Center[Forum]
Login in to Rate this Post:     0       ?        
Namaste!!! to all c++ programmer

The  file named data.txt.  contains a different integers value.This file contains a long list of random numbers.  write a program that opens the file, reads all the numbers from the file, and calculates the following.
A) The number of numbers in the file
B) The sum of all the numbers in the file( a running total)
c) The average of all the numbers in the file.

The program should display the number of numbers found in the file, the sum of the numbers, and the average of the numbers

My ans:

#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
ifstream inputFile;
int number;
int i = 1;
int sum = 0;
double average = 0.0;
 
inputFile.open("data.txt");
if (!inputFile)
cout << "Can not open File.\n";
else
{
while(i < 201)                   // i just count it all the value from the file.
{
if(inputFile >> number)
cout << number << endl;
else
break;
sum +=number;
average = sum/i;
}
inputFile.close();
}
cout <<"Sum is" <<sum <<endl;
cout <<"average is" << average << endl;
 
return 0;
}

I would like to know if there some other way to do it., instead of counting integer value from data.txt file.
 

 
Read Full Discussion Thread for this article