Добавил:
baraevaliza
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Лабы и курсачи 2022-2023 / 1 сем / Baraeva_Elizaveta_lb3
.pdf
МИНОБРНАУКИ РОССИИ
САНКТ-ПЕТЕРБУРГСКИЙ ГОСУДАРСТВЕННЫЙ
ЭЛЕКТРОТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ
«ЛЭТИ» ИМ. В. И. УЛЬЯНОВА (ЛЕНИНА)
Кафедра МО ЭВМ
ОТЧЕТ
по лабораторной работе №3
по дисциплине «Программирование»
Тема: Использование указателей
Студентка гр. 2383
Бараева Е. Н.
Преподаватель
Гаврилов А. В.
Санкт-Петербург
2022

2
Цель работы.
Научиться редактировать текст, используя указатели и выделение памяти,
на языке Си.
Задание.
Напишите программу, которая форматирует некоторый текст и выводит
результат на консоль.
На вход программе подается текст, который заканчивается предложением
"Dragon flew away!".
Предложение (кроме последнего) может заканчиваться на:
• . (точка)
• ; (точка с запятой)
• ? (вопросительный знак)
Программа должна изменить и вывести текст следующим образом:
• Каждое предложение должно начинаться с новой строки.
• Табуляция (\t, ' ') в начале предложения должна быть удалена.
• Все предложения, в которых есть число 555, должны быть удалены.
• Текст должен заканчиваться фразой "Количество предложений до
n и количество предложений после m", где n - количество
предложений в изначальном тексте (без учета терминального
предложения "Dragon flew away!") и m - количество предложений в
отформатированном тексте (без учета предложения про количество
из данного пункта).
Выполнение работы.
В начале была выделена память (с помощью malloc) для 25 предложений
в массив text, затем для каждого предложения была выделена память по 50
символов. Созданы переменные для подсчёта предложений до и после
(sentences_after, sentences_before) и счетчик предложений N. После этого с
помощью двух циклов while были записаны предложения в массив. Каждый

3
символ считывался с помощью getchar(), а до выделение памяти происходило
с помощью realloc. Если попадался символ конца предложения, то в конце
предложения записывался символ переноса строки и конца строки, после
этого происходил выход из последнего цикла, производилась проверка на
конец текста, до выделялась память для следующих предложений,
записывание символов переходило в следующее предложение. После записи
всего текста проходила проверка на число 555. Если в предложении
встречалось отдельно стоящее число 555, то это предложение не выводилось
на экран, а остальные выводились. Затем выводилось предложение с
количеством предложений до и после. В конце программы очищалась память
с помощью free().
Разработанный программный код см. в приложении А.
Тестирование.
Результаты тестирования представлены в табл. 1.

4
Таблица 1 – Результаты тестирования
№ п/п
Входные данные
Выходные данные
Комментарии
1.
Nulla facilisi. Class
aptenT taciti sociosqu ad
litora torquent per
cOnubia nostra, per
inceptos himenaeos. 40
Nu555lla rutrum feugiat
felis a pharetra. Sed
finibus magna et mauris
elementum tempus?
Integer at quam et erat
iaculis iaculis hendrerit a
te4llus? Donec at nunc ac
mauris suscipit venenatis.
Sed finibus magna et
mauris elementum
tempus? Lorem ipsum
dolor sit amet,
consectetur adipiscing
elit. Morbi
co7ndimentum 555 ex
justo, nec pharetra mauris
vestibulum a.
Suspendisse quis mi
neque7. 1 Vivamus eu
nibh rhoncus, da456pibus
ex non, sodales mi.
Donec accumsan
convallis ipsum vitae
lacinia. Donec accumsan
convallis ipsum vitae
lacinia. Fusce finibus
sapien magna, quis
scelerisque ex sodales
tristique. Nulla facilisi.
Lorem ipsum dolor sit
amet, consectetur
adipiscing elit. Dragon
flew away!
Nulla facilisi.
Class aptenT taciti sociosqu
ad litora torquent per
cOnubia nostra, per
inceptos himenaeos.
40 Nu555lla rutrum feugiat
felis a pharetra.
Sed finibus magna et
mauris elementum tempus?
Integer at quam et erat
iaculis iaculis hendrerit a
te4llus?
Donec at nunc ac mauris
suscipit venenatis.
Sed finibus magna et
mauris elementum tempus?
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Suspendisse quis mi
neque7.
1 Vivamus eu nibh rhoncus,
da456pibus ex non, sodales
mi.
Donec accumsan convallis
ipsum vitae lacinia.
Donec accumsan convallis
ipsum vitae lacinia.
Fusce finibus sapien magna,
quis scelerisque ex sodales
tristique.
Nulla facilisi.
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Dragon flew away!
Количество предложений
до 16 и
количество предложений
после 15
Верно
2.
Jack was hungry. He
walked to the kitchen; He
got out some eggs. He
took out some oil. He
Jack was hungry.
He walked to the kitchen;
He got out some eggs.
He took out some oil.
Верно

5
placed a skil555let on the
stove; Next, he turned on
the heat? He poured the
oil into the skillet. He
cracked the 555 eggs into
a bowl. He stirred the
eggs. Then, he poured
them into the hot skillet.
He waited while the eggs
cooked? They cooked for
655578 minutes. He
heard them cooking.
They popped in the oil.
Next, Jack put the eggs
on a plate. He placed the
plate on the dining room
table. Jack loved looking
at his eggs; They looked
pretty on the white plate.
He sat down in the large
wooden chair? He
thought about the day
ahead. He ate the eggs
with a spoon. They were
good.
He washed the plate with
dishwashing soap5555.
Then, he washed the pan.
He got a sponge damp;
Finally, he wiped down
the table 555. Next, Jack
watched TV?
Dragon flew away!
He placed a skil555let on
the stove;
Next, he turned on the heat?
He poured the oil into the
skillet.
He stirred the eggs.
Then, he poured them into
the hot skillet.
He waited while the eggs
cooked?
They cooked for 655578
minutes.
He heard them cooking.
They popped in the oil.
Next, Jack put the eggs on a
plate.
He placed the plate on the
dining room table.
Jack loved looking at his
eggs;
They looked pretty on the
white plate.
He sat down in the large
wooden chair?
He thought about the day
ahead.
He ate the eggs with a
spoon.
They were good.
He washed the plate with
dishwashing soap5555.
Then, he washed the pan.
He got a sponge damp;
Next, Jack watched TV?
Dragon flew away!
Количество предложений
до 27 и
количество предложений
после 25
Вывод.
Была изучена работа по редактированию текста с использованием
указателей и выделения памяти на языке Си.

6
ПРИЛОЖЕНИЕ А
ИСХОДНЫЙ КОД ПРОГРАММЫ
Название файла: main_lb3.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(){
char **text = malloc(sizeof(char*) * 25), c;
int N = 0, size_str = 25, sentences_after = -1,
sentences_before = 0;
for(int i = 0; i < 25; i++){
text[i] = malloc(sizeof(char) * 50);
}
while(1){
int j = 0, size_sent = 50;
while (1){
c = (char) getchar();
if (j % (size_sent - 1) == 0){
text[N] = realloc(text[N], sizeof(char) * (50 +
size_sent));
size_sent += 50;
}
text[N][j] = c;
if (c == '.' || c == ';' || c == '?' || c == '!'){
if (j % (size_sent - 1) == 0 || (j - 1) %
(size_sent - 2) == 0){
text[N] = realloc(text[N], sizeof(char) * (2
+ size_sent));
}
text[N][++j] = '\n';
text[N][++j] = '\0';
if(c != '!'){
sentences_before++;
}
N++;
c = (char) getchar();
break;
}
j++;
}
if (text[N - 1][j - 2] == '!'){
break;
}
if (N % (size_str - 1) == 0){
text = realloc(text, sizeof(char *) * (25 +
size_str));
size_str += 25;
}
}
int str_555 = 0;
for(int i = 0; i < N; i++){
for(int j = 0; j < strlen(text[i]) - 4 ; j++){

7
if ((!isalnum(text[i][j]) && text[i][j+1] == '5' &&
text[i][j+2] == '5' && text[i][j+3] == '5' && !isalnum(text[i][j+4]))
|| (j == 0 && text[i][j] == '5' && text[i][j+1] == '5' && text[i][j+2]
== '5' && !isalnum(text[i][j+3]))){
str_555++;
break;
}
}
if(str_555 == 0){
printf("%s", text[i]);
sentences_after++;
}
str_555 = 0;
}
printf("Количество предложений до %d и количество предложений
после %d", sentences_before, sentences_after);
for(int i = 0; i < N; i++){
free(text[i]);
}
free(text);
return 0;
}
Соседние файлы в папке 1 сем
