Username77177

Dahl-Programming-Lab13-16

Apr 5th, 2020
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.53 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3. #include <string>
  4. #include <sys/types.h>
  5. #include <type_traits>
  6. using namespace std;
  7.  
  8. int main() {
  9.   // Задача 1. Подсчитать количество слов в чётных строках текста, учитывая, что
  10.   // исходная информация хранится в текстовом файле.
  11.  
  12.   // Check amount of rows
  13.   ifstream line("../textfile");
  14.   string our_file_in_str;
  15.   __int16_t amount_of_lines = 0,
  16.             spaces = 0; // Tiny variable for checking lines and spaces
  17.   if (line.is_open()) {
  18.     while (getline(line, our_file_in_str)) {
  19.       ++amount_of_lines;
  20.     }
  21.     cout << "Amount of lines: " << amount_of_lines << endl;
  22.     line.close();
  23.   }
  24.  
  25.   ifstream input_file("../textfile");
  26.   if (input_file.is_open()) {
  27.     cout << "File is opened!\n";
  28.     for (int i = 0; i < amount_of_lines; i++) {
  29.       if (i % 2 == 1) // Bcz, 1 == second row in the file
  30.       {
  31.         getline(input_file, our_file_in_str);
  32.         for (auto i : our_file_in_str) // Checking for spaces (amount of spaces
  33.                                        // + 1 = amount of words)
  34.         {
  35.           if (i == ' ') {
  36.             spaces++;
  37.           }
  38.         }
  39.       } else {
  40.         getline(input_file, our_file_in_str); // Skip the string
  41.         //                cout << our_file_in_str << endl;
  42.       }
  43.     }
  44.     cout << "Amount of spaces: " << spaces << "\n";
  45.     input_file.close();
  46.   } else
  47.  
  48.   {
  49.     cout << "I can't find any file!" << endl;
  50.   }
  51.  
  52.   //Задача 2. Написать программу, которая считывает текст из файла и выводит его
  53.   //на экран, меняя местами каждые два соседних слова.
  54.   // 1. Считать текст из файла
  55.   // 2. Преобразовать текст из файла в строковый массив
  56.   // 3. Вывести с помощью цикла for
  57.   ifstream file("test.cpp");
  58.   if (file.is_open()) {
  59.     string word, word2;
  60.     int index_of_word = 1;
  61.     while (file >> word2) {
  62.       if (index_of_word % 2 == 0) {
  63.         cout << word2 << " " << word << " ";
  64.       } else {
  65.         word = word2;
  66.       }
  67.       index_of_word++;
  68.     }
  69.     file.close();
  70.   }
  71.   // if (file.is_open())
  72.   //{
  73.   // string str, str2;
  74.   // int word_count;
  75.   // while (file >> str)
  76.   //{
  77.   // cout << str << " ";
  78.   //}
  79.   // file.close();
  80.   //}
  81.   else {
  82.     cout << "I can't find your file!\n";
  83.   }
  84.  
  85.   return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment