Робота з файлами
Виконав:
Студентка 1 курсу ФТІ
групи ФБ-22
Трішина Е.Є.
Перевірив:
Поздняков Є.А.
Ткач В.М.
Лабораторна робота №5
1. Мета роботи:
Отримати навички роботи з файлами з використанням засобів мови С++
2. Завдання:
В файлі test.in записано текст англійською мовою. Замініть всі входження слова “Hello” на слово “World”. Результат запишіть в test.out. Для роботи з файлами використовуйте функції fstream
Частина 2:
Створіть програму, що буде знаходити всі текстові строки довжиною більше 5 символі
Частина 3:
Створіть програму, що підраховує частоти входження слів в текстовому файлі.
3. Код програми
Частина 1:
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile ("1.txt");
ofstream outfile ("2.txt");
if (! infile)
{
cerr << "Error.\n";
return -1;
}
if (! outfile) {
cerr << "Error.\n";
return -2;
}
string c,b;
c = "Hello";
b = "World";
string textline;
while (getline(infile, textline, '\n'))
while (infile >> c)
{
outfile << b << endl;
|
|
}
return 0;
}
Частина 2:
#include "stdafx.h"
#include <conio.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string file_name;
cout << "enter name of your file" <<endl;
cin >> file_name;
ifstream infile (file_name.c_str(), ios::in);
if (! infile)
{
cerr << "error";
return (-1);
}
else cout << "\n";
string textline;
while (getline(infile, textline, '\n'))
{
if (textline.size() > 5) {
cout << "line:" << textline << endl;
}
}
getch();
return 0;
}
Частина 3
#include "stdafx.h"
#include <conio.h>
#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <string>
using namespace std;
int main()
{
string file_name;
cout << "enter name of your file" <<endl;
cin >> file_name;
ifstream file(file_name);
if(!file.is_open()){
cout << "Error open file" << endl;
return -1;
}
string word;
cout << "enter word you need to find" << endl;
cin >> word;
cout << "The quantity is =";
cout << count_if(istream_iterator<string>(file), istream_iterator<string>(), bind2nd(equal_to<string>(), word)) << endl;
getch();
return 0;
}
Скріншоти виконання