Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <fstream>
- #include <algorithm>
- using namespace std;
- double findMaxEl(vector<double> arr, double maxEl, int i) {
- if(i < arr.size()) {
- double el = arr[i];
- if(el > maxEl)
- maxEl = el;
- return findMaxEl(arr, maxEl, i+1);
- }
- return maxEl;
- }
- vector<string> split(string str, string delimiter) {
- vector<string> result;
- int pos = 0;
- while(pos != -1) {
- pos = str.find(delimiter);
- result.push_back(str.substr(0, pos));
- str.erase(0, pos + delimiter.length());
- }
- return result;
- }
- void trim(std::string & src) {
- src.erase(std::find_if_not(src.rbegin(), src.rend(), ::isspace).base(), src.end());
- src.erase(src.begin(), std::find_if_not(src.begin(), src.end(), ::isspace));
- }
- string chooseInputType() {
- string type;
- bool notCorrect = true;
- cout << "Введите [c], если хотите произвести ввод из консоли, либо [f], если хотите произвести ввод из файла." << endl;
- while(notCorrect) {
- getline(cin, type);
- if(type == "c" || type == "f")
- notCorrect = false;
- else
- cout << "Введите либо [c], либо [f]" << endl;
- }
- return type;
- }
- vector<double> inputSequenceFromConsole() {
- vector<double> sequence;
- bool continueCycle = true;
- int i = 1;
- cout << "Введите число, либо [стоп], чтобы прекратить ввод" << endl;
- while(continueCycle) {
- cout << "Введите " << i << "-й элемент последовательности" << endl;
- string input;
- getline(cin, input);
- if(input == "стоп") {
- if(sequence.size() > 1)
- continueCycle = false;
- else
- cout << "Введите хотя бы 2 элемента последовательности." << endl;
- } else if(input.length() > 0) {
- try {
- double el = stod(input);
- sequence.push_back(el);
- i++;
- } catch (...) {
- cout << "Вводимый элемент должен быть вещественным числом, повторите ввод." << endl;
- }
- } else
- cout << "Элемент не может быть пустым, повторите ввод." << endl;
- }
- return sequence;
- }
- void showFileData(ifstream &file) {
- file.seekg(0);
- string str;
- getline(file, str);
- trim(str);
- vector<string> arr = split(str, " ");
- cout << "Массив, введенный в файл:" << endl;
- for(string &el : arr) {
- trim(el);
- cout << el << ' ';
- }
- cout << endl;
- }
- bool isFileCorrect(ifstream &file) {
- bool result = true;
- try {
- file.seekg(0);
- string inputStr;
- getline(file, inputStr);
- trim(inputStr);
- vector<string> nums = split(inputStr, " ");
- if(nums.size() > 1)
- for(string &num : nums)
- stod(num);
- else
- result = false;
- } catch (...) {
- result = false;
- }
- return result;
- }
- ifstream openFile() {
- string filePath;
- bool notCorrect = true;
- ifstream file;
- while(notCorrect) {
- cout << "Введите путь к файлу" << endl;
- getline(cin, filePath);
- file.open(filePath);
- if(file.good()) {
- if(isFileCorrect(file)) {
- notCorrect = false;
- showFileData(file);
- } else
- cout << "В файле должны присутствовать минимум два вещественных числа, разделенные одиночным пробелом и записанные в одну строку. Измените файл и повторите ввод." << endl;
- } else {
- cout << "Произошла ошибка при чтении файла. Убедитесь, что такой файл существует и повторите ввод." << endl;
- notCorrect = true;
- }
- }
- return file;
- }
- vector<double> inputSequenceFromFile() {
- ifstream file = openFile();
- vector<double> sequence;
- file.seekg(0);
- string inputStr;
- getline(file, inputStr);
- trim(inputStr);
- vector<string> nums = split(inputStr, " ");
- file.close();
- for(string num : nums) {
- double el = stod(num);
- sequence.push_back(el);
- }
- return sequence;
- }
- bool areValuesDifferent(vector<double> &arr) {
- bool areDifferent = false;
- double value = arr[0];
- int i = 1;
- while(!areDifferent && i < arr.size()) {
- double el = arr[i];
- if(el != value)
- areDifferent = true;
- i++;
- }
- return areDifferent;
- }
- bool isUserWantToSave() {
- cout << "Хотите сохранить результат в файл? [д/н]" << endl;
- string choice;
- bool notCorrect = true;
- while(notCorrect) {
- getline(cin, choice);
- if(choice == "д" || choice == "н")
- notCorrect = false;
- else
- cout << "Вы должны ввести либо [д], либо [н]" << endl;
- }
- return choice == "д";
- }
- void saveFile(string result) {
- if(isUserWantToSave()) {
- cout << "Введите имя файла" << endl;
- string filePath;
- getline(cin, filePath);
- ofstream outputFile;
- outputFile.open(filePath);
- if(outputFile.is_open()) {
- outputFile << result;
- cout << "Результат успешно сохранен." << endl;
- outputFile.close();
- } else {
- cout << "Произошла ошибка при попытке сохранить файл." << endl;
- }
- }
- }
- void output(vector<double> sequence) {
- if(areValuesDifferent(sequence)) {
- string maxEl = to_string(findMaxEl(sequence, sequence[0], 0));
- const string RESULT_MSG = "Максимальный элемент последовательности = " + maxEl;
- cout << RESULT_MSG << endl;
- saveFile(RESULT_MSG);
- } else
- cout << "Массив состоит из одинаковых значений, найти максимальный элемент невозможно." << endl;
- }
- vector<double> inputSequence(string inputType) {
- if(inputType == "c")
- return inputSequenceFromConsole();
- return inputSequenceFromFile();
- }
- int main() {
- cout << "Данная программа находит максимальный элемент введенной последовательности." << endl;
- string inputType = chooseInputType();
- vector<double> sequence = inputSequence(inputType);
- output(sequence);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement