- •Міністерство освіти та науки україни
- •Аннотация
- •Анотація
- •Лабораторная работа 1 “Одномерный массив - вектор”
- •1. Общие указания
- •2. Пример реализации
- •3. Варианты задания
- •4. Требования к отчету
- •2. Пример реализации
- •3. Варианты задания
- •4. Требования к отчету
- •1.2. Динамические структуры данных: стек, очередь список
- •2. Пример реализации
- •4.Варианты заданий
- •Порядок выполнения работы.
- •Лабораторная работа №4 “Обработка строк”
- •1. Общие указания
- •2.1. Функции ввода/вывода строк
- •2.2. Другие функции работы со строками
- •3. Пример реализации класса «строка»
- •3.1. Класс Слово (word)(строка в одно слово)
- •3.2. Класс Сообщение (Message)(строка длиной до 80 символов (одна экранная строка)
- •3.3. Класс Предложение (sentence) (Строка, состоящая из одного Предложения, занимающего одну или более строк)
- •4. Варианты задания
- •5. Требования к отчету
- •2. Варианты задания
- •3. Содержание отчета
- •Лабораторная работа 6 “Множественное наследование”
- •1. Общие указания
- •4.Варианты заданий
- •Приложение b Терминологический словарь
3. Пример реализации класса «строка»
3.1. Класс Слово (word)(строка в одно слово)
Пример 3.1.
#include <stdio.h>
#include <conio.h>
#include <string.h>
class word
{
char *word;
int l;
public:
word();
~word();
void inpw();
void outw();
void invword();
int getl();
};
word::word()
{
l=20;
word=new char[20];
}
word::~word()
{ delete word;}
void word::inpw() //ввод с клавиатуры
{
printf("\nInput word:");
scanf("%s",word);
l=strlen(word);
} //end of function inpw()
void word::outw() // output to screen
{
printf("%s",word);
} //end of function
void word::invword()
{
int i=0,k=l-1;
char ch;
while (i<k)
{
ch=word[i];
word[i]=word[k];
word[k]=ch;
i++; k--;
}
}
int word::getl()
{ return l;}
void main()
{
clrscr();
word W1;
W1.inpw();
printf("\n Word <");
W1.outw();
printf("> of %d characters ", W1.getl());
W1.invword();
printf(" is word <"); W1.outw();
printf("> in back order");
getch();
}
Результат:
Input word: abcdef
Word <abcdef> of 6 character is word <fedcba> in back order
3.2. Класс Сообщение (Message)(строка длиной до 80 символов (одна экранная строка)
Пример 3.2. (getch())
#include <stdio.h>
#include <conio.h>
class mes
{
char *mes;
int l;
public:
mes();
~mes();
void inpkey();
void outsc();
int c_words();
int getl();
};
mes::mes()
{
l=80;
mes=new char[80];
}
mes::~mes()
{ delete mes;}
void mes::inpkey() //ввод с клавиатуры
{
char ch;
int i;
printf("\nInput string:");
i=0;
while( ((ch=getch())!=13)&&(i<80) )
{putch(ch); mes[i]=ch; i++;}
l=i;
mes[i]='\0'; //end-of-string
} //end of function inpkey()
void mes::outsc() // output to screen
{
int i=0;
char ch;
while( (ch=mes[i])!='\0')
{ printf("%c",ch); i++; }
} //end of function
int mes::c_words() // подсчет слов в сообщении
{
int i,k=0;
for (i=0; i<l; i++)
if (mes[i]==' ') k++;
return (k+1);
}
int mes::getl()
{ return l;}
void main()
{
clrscr();
mes M1;
M1.inpkey();
printf("\n String <");
M1.outsc();
printf("> of %d characters consists of %d words",
M1.getl(),M1.c_words());
getch();
}
Result:
Input string:I am a student
String < I am a student > of 14 characters consists of 4 words
Пример 3.3 (gets)
#include <stdio.h>
#include <string.h>
#include <conio.h>
class mes
{
char *mes;
int l;
public:
mes();
~mes();
void inp1();
void out1();
int c_words();
int getl();
};
mes::mes()
{
l=80;
mes=new char[80];
}
mes::~mes()
{ delete mes;}
void mes::inp1() //ввод с клавиатуры
{
printf("\nInput string:");
gets(mes);
l=strlen(mes);
} //end of function inp1()
void mes::out1() // output to screen
{
puts(mes);
} //end of function
int mes::c_words()// подсчет слов в сообщении
{
int i,k=0;
for (i=0; i<l; i++)
if (mes[i]==' ') k++;
return (k+1);
}
int mes::getl()
{ return l;}
void main()
{
clrscr();
mes M1;
M1.inp1();
printf("\n String <");
M1.out1();
printf("> of %d caracters consists of %d words",
M1.getl(),M1.c_words());
getch();
mes M2;
M2.inp1();
printf("\n String <");
M2.out1();
printf("> of %d character consists of %d words", M2.getl(),M2.c_words());
getch();
}
3.3. Класс Предложение (sentence) (Строка, состоящая из одного Предложения, занимающего одну или более строк)
Простое повествовательное предложение заканчивается точкой ‘.’ (full stop). Восклицательное предложение заканчивается ‘!’ (exclamation mark). А вопросительное предложение заканчивается ‘?’ (question-mark).
#include <stdio.h>
#include <string.h>
#include <conio.h>
class sent
{
char *sent;
int l;
public:
sent();
~sent();
void inpf(FILE *f);
void savef(FILE *f);
int c_words();
int getl();
void edit();
};
sent::sent()
{
l=2000;//25*80
sent=new char[2000];
}
sent::~sent()
{ delete sent;}
void sent::inpf(FILE *f) //input from file
{
int i; char ch;
i=0;
ch=fgetc(f);
while( (ch!='.')&&(ch!='!')&&(ch!='?') )
{ sent[i]=ch; i++;
ch=fgetc(f);
}
sent[i]=ch; i++;
l=i;
sent[i]='\0';
} //end of function inpf()
void sent::savef(FILE *f) // output to file
{
int i=0; char ch;
while ((ch=sent[i])!='\0')
{
putc(ch,f); i++;
}
} //end of function
int sent::c_words() // count of words in sentence
{
int i,k=0;
for (i=0; i<l; i++)
if (sent[i]==' ') k++;
return (k+1);
}
int sent::getl()
{ return l;}
void sent::edit()
{
//replace two or more blanks by one
int i=0,k=0;
char ch;
while ((sent[i]!=' ')&&(sent[i]!='\0'))
{ i++; k++; }
i++;k++;
while (sent[i]==' ') i++;
while (sent[i]!='\0')
{
while ((sent[i]!=' ')&&(sent[i]!='\0'))
{ sent[k]=sent[i]; i++; k++; }
if (sent[i]!='\0')
{ sent[k]=' ';i++; k++;
while (sent[i]==' ') i++;
}
}
//delete blank befor the sentence-end-mark
if (sent[k-2]==' ') {sent[k-2]=sent[k-1]; k--;}
l=k; sent[l]='\0';
}
void main()
{
clrscr();
sent S1;
FILE *f1;
f1=fopen("Sent.dat","r");
FILE *f2;
f2=fopen("Sent_res.dat","w+");
S1.inpf(f1);
fprintf(f2,"\n Sentence <");
S1.savef(f2);
fprintf(f2,"> of %d characters consists of %d words",
S1.getl(),S1.c_words());
S1.edit();
fprintf(f2,"\n After edition sentence <");
S1.savef(f2);
fprintf(f2,"> of %d characters consists of %d words",
S1.getl(),S1.c_words());
fclose(f1);
fclose(f2);
getch();
}
Проверим эту программу для различных предложений.
1) Например, для файла “sent.dat”
This is a first sentence.
Результирующий файл ( “sent_res.dat”) содержит:
Sentence <This is a first sentence.> of 35 characters consists of 15 words
After edition sentence <This is a first sentence.> of 25 characters consists of 5 words
2) Для файла “sent.dat” , содержащего
Is this a first sentence ?
Результирующий файл ( “sent_res.dat”) будет содержать:
Sentence <Is this a first sentence ?> of 38 characters consists of 18 words
After edition sentence <Is this a first sentence?> of 25 characters consists of 5 words
3) Для файла “sent.dat” , содержащего
Is this a first sentence
of our very long text or
this is a second
sentence of small file ?
Результирующий файл ( “sent_res.dat”) будет содержать:
Sentence <Is this a first sentence
of our very long text or
this is a second
sentence of small file ?> of 144 characters consists of 70 words
After edition sentence <Is this a first sentence
of our very long text or
this is a second
sentence of small file?> of 92 characters consists of 18 words