### Author Topic: Application file streams I/O  (Read 7862 times)

#### louiecerv

• Moderator
• User
• Posts: 85
##### Application file streams I/O
« on: February 06, 2006, 09:58:59 AM »
Write a program that takes its input from a  file of numbers of type double. The program outputs to the screen the average and standard deviation of the numbers in a the file.  The file contains nothing but numbers of type double separated by blanks or line breaks.  The standard deviation of a list of numbers is defined as the square root of the average of the deviations.

SOLUTION

Code: [Select]
`#include <iostream>#include <fstream>#include <cmath>using namespace std;double getAverage();double standardDeviation(double average);int main(){    cout << "* A PROGRAM TO COMPUTE STANDARD DEVIATION * \n";    cout << "Input data is read from the file \"datafile.txt\" \n\n";    double average, sd;    average = getAverage();    sd = standardDeviation(average);        cout.setf(ios::showpoint);    cout.setf(ios::fixed);        cout.precision(4);    cout << "\nAverage            : " << average << endl;    cout << "Standard Deviation : " << sd << endl;        system("PAUSE");    return 0;}double getAverage(){     ifstream fin;     double next, sum=0, count=0;     fin.open("datafile.txt");     fin >> next;     while(! fin.eof() )     {         sum+=next;         count++;         fin >> next;     }     double average = sum/count;     fin.close();     return average;}double standardDeviation(double average){     ifstream fin;     double next, totaldev=0, count=0;     fin.open("datafile.txt");          fin >> next;     while(! fin.eof() )     {         cout << next << endl;         totaldev += pow(next-average, 2.0);         count++;         fin >> next;     }     double sd = sqrt(totaldev/count);     fin.close();     return sd;}`
Analyze. Design. Develop. Debug. Deploy. Maintain.

#### louiecerv

• Moderator
• User
• Posts: 85
##### Improve by checking file exists first
« Reply #1 on: February 06, 2006, 10:00:32 AM »
Improve this solution by checking that the file exists before reading the data.
Analyze. Design. Develop. Debug. Deploy. Maintain.