Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <cmath>
- #include <fstream>
- #include <string>
- #include <cstdlib>
- #include <vector>
- std::string const file_name_i("./input.txt");
- std::string const file_name_o("./output.txt");
- std::vector<int> read_data(std::string const file_name);
- void analysis(std::vector<int> collect,
- std::string const file_name,
- bool serialize = false);
- int main() {
- std::vector<int> collect;
- collect = read_data(file_name_i);
- // analysis
- analysis(collect, file_name_o, true);
- return 0;
- }
- // FZ
- std::vector<int> read_data(std::string const file_name) {
- std::vector<int> collect;
- std::ifstream inStream;
- inStream.open(file_name);
- if (!inStream.is_open()) {
- std::string emsg("File open error: ");
- emsg += file_name;
- throw std::runtime_error(emsg);
- }
- while (!inStream.eof()) {
- int x_;
- // just read the file and save data into a vector
- // allows analysis of the data independent of I/O
- inStream >> x_;
- collect.push_back(x_);
- }
- // resource cleanup
- inStream.close();
- return collect;
- }
- void analysis(std::vector<int> collect,
- std::string const file_name,
- bool serialize) {
- std::ofstream outStream;
- std::streambuf * coutbuf;
- if (serialize) {
- outStream.open(file_name);
- if (!outStream.is_open()) {
- std::string emsg("File open error: ");
- emsg += file_name;
- throw std::runtime_error(emsg);
- }
- coutbuf = std::cout.rdbuf();
- std::cout.rdbuf(outStream.rdbuf());
- }
- std::cout << "=== === ============" << std::endl;
- std::cout << " x x^2 Current Sum." << std::endl;
- std::cout << "=== === ============" << std::endl;
- int sum = 0;
- for (auto xx : collect) {
- sum += xx;
- double pwr = pow(xx, 2);
- std::cout << std::setw(2)
- << xx
- << std::setw(5)
- << pwr
- << std::setw(8)
- << sum
- << std::endl; // isspace(int, pow)
- }
- double avg = (static_cast<double>(sum) / collect.size());
- std::cout << '\n'
- << "The average of these "
- << collect.size()
- << " numbers is: "
- << avg
- << std::endl;
- if (serialize) {
- // resource cleanup
- std::cout.rdbuf(coutbuf);
- outStream.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement