#include #include #include #include #include #include inline double to_2(double x) { return x * x; } class InsuficientDataException { }; double stdev(std::vector const &v) { size_t N = v.size(); if (N < 2) { throw InsuficientDataException(); } double s{0}; for (auto &x: v) { s += x; } double m{s / N}; s = 0; for (auto &x: v) { s += to_2(x - m); } return sqrt(s / (N - 1)); } class FileException { }; class FileNotFoundException : public FileException { }; class FileReadException : public FileException { }; double stdev_from_file(std::string filename) { std::ifstream file(filename); if (! file.good()) { throw FileNotFoundException(); } file.exceptions(std::ios::failbit | std::ios::badbit); std::vector v; try { int N; file >> N; v.resize(N); for (int i = 0; i < N; ++i) { file >> v[i]; } } catch (std::ifstream::failure e) { throw FileReadException(); } return stdev(v); } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " \n"; exit(1); } double val; try { val = stdev_from_file(argv[1]); std::cout << "The standard deviation is " << val << std::endl; } catch (FileNotFoundException &e) { std::cerr << "The file " << argv[1] << " does't exist.\n"; return 1; } catch (FileReadException &e) { std::cerr << "The file " << argv[1] << " is not in the expected format.\n"; return 1; } catch (FileException &e) { // Esta poderia pegar as duas anteriores (experimente comentar). std::cerr << "Something wrong with the file " << argv[1] << std::endl; } catch (InsuficientDataException &e) { std::cerr << "Not enough values to compute standard deviation.\n"; } return 0; }