Advertisement
Alyks

Untitled

Mar 24th, 2020
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 6.98 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <fstream>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. double findMaxEl(vector<double> arr, double maxEl, int i) {
  9.     if(i < arr.size()) {
  10.         double el = arr[i];
  11.         if(el > maxEl)
  12.             maxEl = el;
  13.         return findMaxEl(arr, maxEl, i+1);
  14.     }
  15.     return maxEl;
  16. }
  17.  
  18. vector<string> split(string str, string delimiter) {
  19.     vector<string> result;
  20.     int pos = 0;
  21.     while(pos != -1) {
  22.         pos = str.find(delimiter);
  23.         result.push_back(str.substr(0, pos));
  24.         str.erase(0, pos + delimiter.length());
  25.     }
  26.     return result;
  27. }
  28.  
  29. void trim(std::string & src) {
  30.     src.erase(std::find_if_not(src.rbegin(), src.rend(), ::isspace).base(), src.end());
  31.     src.erase(src.begin(), std::find_if_not(src.begin(), src.end(), ::isspace));
  32. }
  33.  
  34. string chooseInputType() {
  35.     string type;
  36.     bool notCorrect = true;
  37.     cout << "Введите [c], если хотите произвести ввод из консоли, либо [f], если хотите произвести ввод из файла." << endl;
  38.     while(notCorrect) {
  39.         getline(cin, type);
  40.         if(type == "c" || type == "f")
  41.             notCorrect = false;
  42.         else
  43.             cout << "Введите либо [c], либо [f]" << endl;
  44.     }
  45.     return type;
  46. }
  47.  
  48. vector<double> inputSequenceFromConsole() {
  49.     vector<double> sequence;
  50.     bool continueCycle = true;
  51.     int i = 1;
  52.     cout << "Введите число, либо [стоп], чтобы прекратить ввод" << endl;
  53.     while(continueCycle) {
  54.         cout << "Введите " << i << "-й элемент последовательности" << endl;
  55.         string input;
  56.         getline(cin, input);
  57.         if(input == "стоп") {
  58.             if(sequence.size() > 1)
  59.                 continueCycle = false;
  60.             else
  61.                 cout << "Введите хотя бы 2 элемента последовательности." << endl;
  62.         } else if(input.length() > 0) {
  63.             try {
  64.                 double el = stod(input);
  65.                 sequence.push_back(el);
  66.                 i++;
  67.             } catch (...) {
  68.                 cout << "Вводимый элемент должен быть вещественным числом, повторите ввод." << endl;
  69.             }
  70.         } else
  71.             cout << "Элемент не может быть пустым, повторите ввод." << endl;
  72.     }
  73.     return sequence;
  74. }
  75.  
  76. void showFileData(ifstream &file) {
  77.     file.seekg(0);
  78.     string str;
  79.     getline(file, str);
  80.     trim(str);
  81.     vector<string> arr = split(str, " ");
  82.     cout << "Массив, введенный в файл:" << endl;
  83.     for(string &el : arr) {
  84.         trim(el);
  85.         cout << el << ' ';
  86.     }
  87.     cout << endl;
  88. }
  89.  
  90. bool isFileCorrect(ifstream &file) {
  91.     bool result = true;
  92.     try {
  93.         file.seekg(0);
  94.         string inputStr;
  95.         getline(file, inputStr);
  96.         trim(inputStr);
  97.         vector<string> nums = split(inputStr, " ");
  98.         if(nums.size() > 1)
  99.             for(string &num : nums)
  100.                 stod(num);
  101.         else
  102.             result = false;
  103.     } catch (...) {
  104.         result = false;
  105.     }
  106.     return result;
  107. }
  108.  
  109. ifstream openFile() {
  110.     string filePath;
  111.     bool notCorrect = true;
  112.     ifstream file;
  113.     while(notCorrect) {
  114.         cout << "Введите путь к файлу" << endl;
  115.         getline(cin, filePath);
  116.         file.open(filePath);
  117.         if(file.good()) {
  118.             if(isFileCorrect(file)) {
  119.                 notCorrect = false;
  120.                 showFileData(file);
  121.             } else
  122.                 cout << "В файле должны присутствовать минимум два вещественных числа, разделенные одиночным пробелом и записанные в одну строку. Измените файл и повторите ввод." << endl;
  123.         } else {
  124.             cout << "Произошла ошибка при чтении файла. Убедитесь, что такой файл существует и повторите ввод." << endl;
  125.             notCorrect = true;
  126.         }
  127.     }
  128.     return file;
  129. }
  130.  
  131. vector<double> inputSequenceFromFile() {
  132.     ifstream file = openFile();
  133.     vector<double> sequence;
  134.     file.seekg(0);
  135.     string inputStr;
  136.     getline(file, inputStr);
  137.     trim(inputStr);
  138.     vector<string> nums = split(inputStr, " ");
  139.     file.close();
  140.     for(string num : nums) {
  141.         double el = stod(num);
  142.         sequence.push_back(el);
  143.     }
  144.     return sequence;
  145. }
  146.  
  147. bool areValuesDifferent(vector<double> &arr) {
  148.     bool areDifferent = false;
  149.     double value = arr[0];
  150.     int i = 1;
  151.     while(!areDifferent && i < arr.size()) {
  152.         double el = arr[i];
  153.         if(el != value)
  154.             areDifferent = true;
  155.         i++;
  156.     }
  157.     return areDifferent;
  158. }
  159.  
  160. bool isUserWantToSave() {
  161.     cout << "Хотите сохранить результат в файл? [д/н]" << endl;
  162.     string choice;
  163.     bool notCorrect = true;
  164.     while(notCorrect) {
  165.         getline(cin, choice);
  166.         if(choice == "д" || choice == "н")
  167.             notCorrect = false;
  168.         else
  169.             cout << "Вы должны ввести либо [д], либо [н]" << endl;
  170.     }
  171.     return choice == "д";
  172. }
  173.  
  174. void saveFile(string result) {
  175.     if(isUserWantToSave()) {
  176.         cout << "Введите имя файла" << endl;
  177.         string filePath;
  178.         getline(cin, filePath);
  179.         ofstream outputFile;
  180.         outputFile.open(filePath);
  181.         if(outputFile.is_open()) {
  182.             outputFile << result;
  183.             cout << "Результат успешно сохранен." << endl;
  184.             outputFile.close();
  185.         } else {
  186.             cout << "Произошла ошибка при попытке сохранить файл." << endl;
  187.         }
  188.     }
  189. }
  190.  
  191. void output(vector<double> sequence) {
  192.     if(areValuesDifferent(sequence)) {
  193.         string maxEl = to_string(findMaxEl(sequence, sequence[0], 0));
  194.         const string RESULT_MSG = "Максимальный элемент последовательности = " + maxEl;
  195.         cout << RESULT_MSG << endl;
  196.         saveFile(RESULT_MSG);
  197.     } else
  198.         cout << "Массив состоит из одинаковых значений, найти максимальный элемент невозможно." << endl;
  199. }
  200.  
  201. vector<double> inputSequence(string inputType) {
  202.     if(inputType == "c")
  203.         return inputSequenceFromConsole();
  204.     return inputSequenceFromFile();
  205. }
  206.  
  207. int main() {
  208.     cout << "Данная программа находит максимальный элемент введенной последовательности." << endl;
  209.     string inputType = chooseInputType();
  210.     vector<double> sequence = inputSequence(inputType);
  211.     output(sequence);
  212.     return 0;
  213. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement