February 14th, 2008, 11:40 PM
|
#1 (permalink)
|
| Junior Member
Join Date: Feb 2008
Posts: 2
| C++: Recognising characters and numbers for the std deviation
Hi,
I've almost completed my first c++ programming assignment that calculates the mean, standard deviation of the distribution and standard deviation of the mean.
Everything runs smoothly when a file of numbers is opened with my program, all the values for the mean...etc...are correct.
However i'm having major problems when there is an inclusion of a character in a file that I open. For example the following sequence
2 4 5 7 4 g 6 h j 7.
My program reads the 2,4,5,7,4 but then ignores everything after the first letter that is part of the sequence. I just want to create an error message for when there are characters on the input file.
any help is appreciated, thank you
P.S how does the programme look for an absolute beginner ? Code: include <cmath> // for math calculations #include <iostream> // for general input/output #include <fstream> // for file input/output #include <cstdlib> // for memory management #include <string> // string used to replace char usingnamespace std; double mean(double * Array, double N); double std_dev(double * Array, double N); // declaring 2 prototype functions int main(){ double array[10000]; // declaring an array holding 10000 integers constint Y = 5000; // number of integers allowed in file string infilename; cout << "Please enter the input filename. "<< endl; cin >> infilename; // inputting and reading input filename ifstream in(infilename.c_str()); if(!in){ cerr << "Failed to open input file " << infilename << endl; exit(1); } // error in reading the input file int i = 0; while(in){ if(i >= Y) break; // close file if integer limit exceeded if(in >> array[i]) i++; // close at end of file } in.clear(); in.close(); // closing input file double M = mean ( array, i); double S = std_dev ( array, i); double SM = S/i; // declaring Mean, Standard deviation and Standard deviation of mean cout << " There are "<< i << " numbers" << endl; cout << " The mean is " << M << endl; cout << " The standard deviation of the distribution is " << S << endl; cout << " The standard deviation of the mean is " << SM << endl; } // writing output closing it double mean (double * array, double N) { double sum = 0 ; for (int i = 0; i < N; i++) sum = sum + array [i]; return sum/N; } // function calculating mean double std_dev (double * array, double N) { double sum = 0; double STD_DEV = 0; // returning zero's for (int i = 0; i < N; i++) { sum = sum + array [i]; STD_DEV = STD_DEV + pow(array [i], 2); } return sqrt ((STD_DEV/N) - (pow(sum/N,2))); } // function calculating standard deviation |
| |