design and implement a c++ function that accepts the path of a file, reads the values a set of numbers from the file and returns the mean and the standard deviation of the numbers in there
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
using namespace std;
void readNumbers(string pathOfTheFile)
{
fstream read(pathOfTheFile);
if(read.is_open())
{
vector<double> numbers;
double number;
while(!read.eof())
{
read >> number;
numbers.push_back(number);
}
double sum = 0;
for(int i = 0; i < numbers.size(); i++)
sum+=numbers[i];
double mean = sum/numbers.size();
cout << "Mean is " << mean << endl;
double standardDeviation = 0;
for(int i = 0; i < numbers.size(); i++)
{
standardDeviation+=pow(numbers[i]-mean,2)/numbers.size();
}
standardDeviation = pow(standardDeviation, 0.5);
cout << "Standard deviation is " << standardDeviation << endl;
}
else
cout << "File not found";
read.close();
}
int main()
{
cout << "Enter path: ";
string pathOfTheFile;
getline(cin, pathOfTheFile);
readNumbers(pathOfTheFile);
cout << endl;
return 0;
}
Explanation : create a file, for example numbers.txt and fill with the following numbers : 3 4 5 1 6 8 10 2 7 (all in one row), save the file, then run a program
Comments