redmanexe

Lab3Challenge2CPP

Nov 2nd, 2024
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 7.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_set>
  3. #include <fstream>
  4.  
  5. using namespace std;
  6.  
  7. constexpr string DEFAULT_INPUT_FILE = "./input.txt";
  8. constexpr string DEFAULT_OUTPUT_FILE = "./output.txt";
  9.  
  10. constexpr int PRINT_TYPE_MIN = 0;
  11. constexpr int PRINT_TYPE_MAX = 2;
  12.  
  13. constexpr int SCAN_TYPE_MIN = 0;
  14. constexpr int SCAN_TYPE_MAX = 1;
  15.  
  16. string calculate(const string &value)
  17. {
  18.     string result;
  19.     const unordered_set set{'+', '-', '*', '/', '.', ',', '=', '^', '%', '0', '2', '4', '6', '8'};
  20.  
  21.     for(int i = 0; i < value.length(); i++)
  22.         if (set.contains(value[i]))
  23.             result += value[i];
  24.  
  25.     return result;
  26. }
  27. bool isTextFile(const string &filePath)
  28. {
  29.     bool isTxt;
  30.     isTxt = (filePath.length() > 4 &&
  31.                 filePath[filePath.length() - 4] == '.' &&
  32.                 filePath[filePath.length() - 3] == 't' &&
  33.                 filePath[filePath.length() - 2] == 'x' &&
  34.                 filePath[filePath.length() - 1] == 't');
  35.  
  36.     return isTxt;
  37. }
  38. bool checkFileAvailability(const string &filePath, const bool read)
  39. {
  40.     ios::openmode mode;
  41.     if (read)
  42.         mode = ifstream::in;
  43.     else
  44.         mode = ifstream::app;
  45.     fstream file(filePath, mode);
  46.     bool available;
  47.     available = file.good();
  48.     file.close();
  49.     if (available && !isTextFile(filePath))
  50.         available = false;
  51.  
  52.     return available;
  53. }
  54. int takeIntValueFromConsole(const string& text)
  55. {
  56.     bool isInCorrect;
  57.     int value;
  58.     isInCorrect = true;
  59.     while (isInCorrect)
  60.     {
  61.         cout << text;
  62.         cin >> value;
  63.         isInCorrect = false;
  64.         if (cin.fail())
  65.         {
  66.             cout << "Введите число, а не строку или что-то иное!\n";
  67.             cin.clear();
  68.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  69.             isInCorrect = true;
  70.         }
  71.     }
  72.  
  73.     return value;
  74. }
  75. int takeIntValueInRangeFromConsole(const string& text, const int min, const int max)
  76. {
  77.     bool isInCorrect;
  78.     int value;
  79.     isInCorrect = true;
  80.     value = 0;
  81.     while (isInCorrect)
  82.     {
  83.         value = takeIntValueFromConsole(text);
  84.         isInCorrect = false;
  85.         if (value < min || value > max)
  86.         {
  87.             cout << "Число должно находится в границах от " << min << " до " << max << "\n";
  88.             cin.clear();
  89.             cin.ignore(numeric_limits<streamsize>::max(), '\n');
  90.             isInCorrect = true;
  91.         }
  92.     }
  93.  
  94.     return value;
  95. }
  96. string takeCorrectFile(const bool input)
  97. {
  98.     bool isInCorrect;
  99.     string value;
  100.     isInCorrect = true;
  101.     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  102.     while(isInCorrect) {
  103.         if (input)
  104.             cout << "Введите путь до входного файла (пустая строка – " << DEFAULT_INPUT_FILE << "): ";
  105.         else
  106.             cout << "Введите путь до выходного файла (пустая строка – " << DEFAULT_OUTPUT_FILE << "): ";
  107.         getline(cin, value);
  108.         if (value.empty())
  109.         {
  110.             if (input)
  111.                 value = DEFAULT_INPUT_FILE;
  112.             else
  113.                 value = DEFAULT_OUTPUT_FILE;
  114.         }
  115.         isInCorrect = false;
  116.         if (!checkFileAvailability(value, input)) {
  117.             isInCorrect = true;
  118.             cout << "Путь ведёт до файла, который недоступен или который не является текстовым файлом!\n";
  119.         }
  120.     }
  121.  
  122.     return value;
  123. }
  124. string takeValueFromFile(ifstream &reader)
  125. {
  126.     string value;
  127.     getline(reader, value);
  128.     reader.clear();
  129.  
  130.     return value;
  131. }
  132. string readStringFromFile()
  133. {
  134.     bool isInCorrect = true;
  135.     string value;
  136.     while (isInCorrect)
  137.     {
  138.         string filePath = takeCorrectFile(true);
  139.         isInCorrect = false;
  140.         ifstream file(filePath);
  141.         value = takeValueFromFile(file);
  142.  
  143.         if (value.empty())
  144.         {
  145.             isInCorrect = true;
  146.             cout << "Строка не может быть пустой!\n";
  147.         }
  148.     }
  149.  
  150.     return value;
  151. }
  152. string readStringFromConsole()
  153. {
  154.     bool isInCorrect = true;
  155.     string value;
  156.     cin.ignore(numeric_limits<streamsize>::max(), '\n');
  157.     while (isInCorrect)
  158.     {
  159.         cout << "Строка для решения: ";
  160.         getline(cin, value);
  161.         isInCorrect = false;
  162.  
  163.         if (value.empty())
  164.         {
  165.             isInCorrect = true;
  166.             cout << "Строка не может быть пустой!\n";
  167.         }
  168.     }
  169.  
  170.     return value;
  171. }
  172. string readString()
  173. {
  174.     int type;
  175.     string value;
  176.     cout << "\nКак считать значения для поиска решения?\n";
  177.     cout << "0 - Из ввода с клавиатуры (консоль)\n";
  178.     cout << "1 - Из файла\n";
  179.     type = takeIntValueInRangeFromConsole("Выбранный вариант ввода: ", SCAN_TYPE_MIN, SCAN_TYPE_MAX);
  180.     if (type == 1)
  181.         value = readStringFromFile();
  182.     else
  183.         value = readStringFromConsole();
  184.  
  185.     return value;
  186. }
  187. bool saveResultIntoFile(const string &filePath, const string &res)
  188. {
  189.     bool saved;
  190.     saved = true;
  191.     ofstream file(filePath);
  192.     if (file.good())
  193.     {
  194.         file << res;
  195.     }
  196.     else
  197.         saved = false;
  198.     file.close();
  199.  
  200.     return saved;
  201. }
  202. void printResult(const string &res)
  203. {
  204.     bool saved;
  205.     int type;
  206.     cout << "\nКуда вывести результат решения?\n";
  207.     cout << "0 - Только консоль\n";
  208.     cout << "1 - Только в файл\n";
  209.     cout << "2 - И в файл, и в консоль\n";
  210.     type = takeIntValueInRangeFromConsole("Выбранный вариант вывода: ", PRINT_TYPE_MIN, PRINT_TYPE_MAX);
  211.     saved = false;
  212.     string output;
  213.     switch (type)
  214.     {
  215.         case 0:
  216.             cout << "\nМножество арифметических знаков и чётных чисел: " << res << "\n";
  217.         break;
  218.         case 1:
  219.             output = takeCorrectFile(false);
  220.             saved = saveResultIntoFile(output, res);
  221.         break;
  222.         case 2:
  223.             output = takeCorrectFile(false);
  224.             saved = saveResultIntoFile(output, res);
  225.             cout << "\nМножество арифметических знаков и чётных чисел: " << res << "\n";
  226.         break;
  227.     }
  228.  
  229.     if (saved)
  230.         cout << "Результат записан в выходной файл!" << "\n";
  231. }
  232.  
  233. int main()
  234. {
  235.     string value, res;
  236.     cout << "2. Дана непустая последовательность символов, требуется построить и напечатать множество, элементами которого являются встречающиеся в последовательности знаки арифметических операций и чётные цифры.\n";
  237.     value = readString();
  238.     res = calculate(value);
  239.     printResult(res);
  240.     return 0;
  241. }
Advertisement
Add Comment
Please, Sign In to add comment