Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
лабы / лаба 11 прога.docx
Скачиваний:
0
Добавлен:
11.02.2026
Размер:
53.33 Кб
Скачать

Ф едеральное агенство воздушного транспорта (росавиация)

ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ

«МОСКОВСКИЙ ГОСУДАРСТВЕННЫЙ ТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ ГРАЖДАНСКОЙ АВИАЦИИ» (МГТУ ГА)

Кафедра вычислительных машин, комплексов, систем и сетей.

Лабораторная работа защищена с оценкой ____________________

____________________

(подпись преподавателя, дата)

ЛАБОРАТОРНАЯ РАБОТА №11

по дисциплине «Программирование».

Вариант №17

Тема: «Разработка программ обработки символьной информации.»

Выполнила студентка группы ИС 1-1

Магальник Екатерина Борисовна

Руководитель: Белозуб Юлия Валерьевна

МОСКВА – 2023

3.1. Цель лабораторной работы

Целью лабораторной работы является получение навыков программирования с использованием методов стандартного класса string для обработки символьной информации, хранящейся в текстовых файлах.

3.2 Задание на выполнение лабораторной работы

Разработать алгоритм и программу обработки символьной информации, хранящейся в текстовом файле в соответствии с вариантом задания. В каждом варианте задания исходным является файл с текстом, состоящий из нескольких предложений.

Текст программы:

#include <iostream>

#include <fstream>

#include <istream>

#include <string>

/*) - Считать текст из файла и вывести его на экран, после каждого предложения добавляя, сколько раз встретилось в нем заданное с клавиатуры слово.

- Закодировать текст файла путем инвертирования его слов. Раскодировать текст и вывести в файл протокола.*/

using namespace std;

string Reverse(string String)

{

int i, j, Temp;

for (i = 0, j = size(String) - 1; i < j; i++, j--)

{

Temp = String[i];

String[i] = String[j];

String[j] = Temp;

}

return String;

}

string Back_Reverse(string String) {

int i, j, Temp;

for (j = 0, i = size(String) - 1; j < i; j++, i--) {

Temp = String[j];

String[j] = String[i];

String[i] = Temp;

}

return String;

}

int main()

{

ifstream fin("C:\\Users\\ACER\\OneDrive\\Desktop\\laba11.txt");

string s;

//getline(fin, s, '\0');

if (!fin) {

cout << "Error! Can't open the file" << endl;

return -1;

}

ofstream out;

out.open("prototype.cpp");

if (out.is_open()) {

out << "Task 1: Read the text from the file and display it on the screen, adding after each sentence how many times the word specified from the keyboard was found in it.";

out << s << endl;

fin.seekg(0, ios::end); //определение длины файла, перемещаясь в его конец

long len = fin.tellg(); //получение длины файла

char* buf = new char[len + 1];

fin.seekg(0, ios::beg); //переносимся в начало файла для чтения

fin.read(buf, len); //чтение из файла

buf[len] = '\0';

char* word = new char[len + 1]; //выделяем место для введенного слова

char* buffer = new char[len + 1]; //выделяем место для предложения

cout << "Enter the word" << endl;

cin >> word;

out << endl;

int l_word = strlen(word), count = 0;

long n = 0, i = 0, j = 0, m = 0;

while (buf[i]) {

if (buf[i] == '.' || buf[i] == '?' || buf[i] == '!') {

for (j = n, m = 0; j <= i; j++, m++) { //цикл для считывания текста

out << buf[j];

buffer[m] = buf[j]; //копирование предложения в буфер

}

buffer[m] = '\0';

char* p = buffer; //указатель на переменную

while (p = strstr(p, word)) { //поиск слова методом сравнения

p += l_word; //увеличение длины подстроки

count++;

}

out << " " << count << " words were found";

count = 0;

n = i + 1;

out << endl;

}

i++;

}

out << endl;

ifstream fout("C:\\Users\\ACER\\OneDrive\\Desktop\\laba11.txt");

string ss;

getline(fout, ss, '\0');

out << ss << endl;

out << "Task 2: Encode the text of a file by inverting its words. Decode the text and output it to the protocol file." << endl;

out << endl;

out << "The reversed text:";

ss = Reverse(ss);

out << ss << endl;

out << endl;

out << "Back reversed text: " << endl;

ss = Back_Reverse(ss);

out << ss << endl;

fout.close();

}

fin.close();

out.close();

return 0;

}

Данные изначального файла:

Today we are going to talk about drones. But what it actually is? Let us start with the definition. An unmanned aerial vehicle (UAV), commonly known as a drone, is an aircraft without any human pilot, crew, or passengers on board. Some interesting fact: it turns out that the word “drone” is actually an abbreviation, that stands for “Dynamic Remotely Operated Navigation Equipment”.

Now it is definitely clear what drone is. But now there is a new question appears. What drones were designed for? UAVs were originally developed through the twentieth century for military missions too "dull, dirty or dangerous" for humans, and by the twenty-first, they had become essential assets to most militaries. Drones are not just actively used for military purposes, they were actually developed precisely as an alternative to aircraft with pilots. In modern conditions, kamikaze drones are actively used, which differ little in their principle of operation from cruise missiles, reconnaissance drones and gunners to collect information and adjust the fire of missile troops, as well as communication drones.

Результат работы программы:

Task 1: Read the text from the file and display it on the screen, adding after each sentence how many times the word specified from the keyboard was found in it.

Today we are going to talk about drones. 1 words were found

But what it actually is? 0 words were found

Let us start with the definition. 0 words were found

An unmanned aerial vehicle (UAV), commonly known as a drone, is an aircraft without any human pilot, crew, or passengers on board. 1 words were found

Some interesting fact: it turns out that the word “drone” is actually an abbreviation, that stands for “Dynamic Remotely Operated Navigation Equipment”. 1 words were found

Now it is definitely clear what drone is. 1 words were found

But now there is a new question appears. 0 words were found

What drones were designed for? 1 words were found

UAVs were originally developed through the twentieth century for military missions too "dull, dirty or dangerous" for humans, and by the twenty-first, they had become essential assets to most militaries. 0 words were found

Drones are not just actively used for military purposes, they were actually developed precisely as an alternative to aircraft with pilots. 0 words were found

In modern conditions, kamikaze drones are actively used, which differ little in their principle of operation from cruise missiles, reconnaissance drones and gunners to collect information and adjust the fire of missile troops, as well as communication drones. 3 words were found

Today we are going to talk about drones. But what it actually is? Let us start with the definition. An unmanned aerial vehicle (UAV), commonly known as a drone, is an aircraft without any human pilot, crew, or passengers on board. Some interesting fact: it turns out that the word “drone” is actually an abbreviation, that stands for “Dynamic Remotely Operated Navigation Equipment”.

Now it is definitely clear what drone is. But now there is a new question appears. What drones were designed for? UAVs were originally developed through the twentieth century for military missions too "dull, dirty or dangerous" for humans, and by the twenty-first, they had become essential assets to most militaries. Drones are not just actively used for military purposes, they were actually developed precisely as an alternative to aircraft with pilots. In modern conditions, kamikaze drones are actively used, which differ little in their principle of operation from cruise missiles, reconnaissance drones and gunners to collect information and adjust the fire of missile troops, as well as communication drones.

Task 2: Encode the text of a file by inverting its words. Decode the text and output it to the protocol file.

The reversed text:

.senord noitacinummoc sa llew sa ,spoort elissim fo erif eht tsujda dna noitamrofni tcelloc ot srennug dna senord ecnassiannocer ,selissim esiurc morf noitarepo fo elpicnirp rieht ni elttil reffid hcihw ,desu ylevitca era senord ezakimak ,snoitidnoc nredom nI .stolip htiw tfarcria ot evitanretla na sa ylesicerp depoleved yllautca erew yeht ,sesoprup yratilim rof desu ylevitca tsuj ton era senorD .seiratilim tsom ot stessa laitnesse emoceb dah yeht ,tsrif-ytnewt eht yb dna ,snamuh rof "suoregnad ro ytrid ,llud" oot snoissim yratilim rof yrutnec hteitnewt eht hguorht depoleved yllanigiro erew sVAU ?rof dengised erew senord tahW .sraeppa noitseuq wen a si ereht won tuB .si enord tahw raelc yletinifed si ti woN

.ќЂвtnempiuqE noitagivaN detarepO yletomeR cimanyDњЂв rof sdnats taht ,noitaiverbba na yllautca si ќЂвenordњЂв drow eht taht tuo snrut ti :tcaf gnitseretni emoS .draob no sregnessap ro ,werc ,tolip namuh yna tuohtiw tfarcria na si ,enord a sa nwonk ylnommoc ,)VAU( elcihev lairea dennamnu nA .noitinifed eht htiw trats su teL ?si yllautca ti tahw tuB .senord tuoba klat ot gniog era ew yadoT

Back reversed text:

Today we are going to talk about drones. But what it actually is? Let us start with the definition. An unmanned aerial vehicle (UAV), commonly known as a drone, is an aircraft without any human pilot, crew, or passengers on board. Some interesting fact: it turns out that the word “drone” is actually an abbreviation, that stands for “Dynamic Remotely Operated Navigation Equipment”.

Now it is definitely clear what drone is. But now there is a new question appears. What drones were designed for? UAVs were originally developed through the twentieth century for military missions too "dull, dirty or dangerous" for humans, and by the twenty-first, they had become essential assets to most militaries. Drones are not just actively used for military purposes, they were actually developed precisely as an alternative to aircraft with pilots. In modern conditions, kamikaze drones are actively used, which differ little in their principle of operation from cruise missiles, reconnaissance drones and gunners to collect information and adjust the fire of missile troops, as well as communication drones.

Соседние файлы в папке лабы