C/C++

Работа с текстовым файлом. С++

После каждого слова текста вставить указанную подстроку.
Требования и общие указания к заданиям:
Необходимо разработать и проверить функции для реализации
следующих действий с текстовым файлом:
 создание файла;
 просмотр файла, т. е. вывод его содержимого на экран;
 добавление текста в файл;
 реализация функциональной части, указанной в варианте, и запись
полученного результата во второй текстовый файл
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
system("chcp 1251 > nul");
cout << "Введите строку текста: ";
string text;
getline(cin, text);
system("cls");
cout << "Введите имя первого файла: ";
string filename;
cin >> filename;
filename += ".txt";
ofstream ofs(filename);
if (ofs.is_open()) {
ofs << text;
ofs.close();
puts("Первый файл сохранён!");
} else {
puts("Не удалось создать первый файл!");
}
ifstream ifs(filename);
string content;
if (ifs.is_open()) {
getline(ifs, content);
cout << "Содержимое первого файла: " << content << '\n';
ifs.close();
} else {
puts("Первый файл не найден!");
}
if (!content.empty()) {
istringstream iss(content);
string word;
vector<string> words;
while (iss >> word) words.push_back(word);
cout << "Введите подстроку: ";
string substr;
cin >> substr;
for (auto& item : words) item += substr;
cout << "Введите имя воторого файла: ";
string second;
cin >> second;
second += ".txt";
ofstream save(second);
if (save.is_open()) {
string line;
for (auto& item : words) line += item + ' ';
line.pop_back();
save << line;
save.close();
puts("Второй файл сохранён!");
ifstream result(second);
string str;
if (result.is_open()) {
getline(result, str);
cout << "Содержимое второго файла: " << str << '\n';
result.close();
} else {
puts("Второй файл не найден!");
}
} else {
puts("Не удалось создать второй файл!");
}
}
system("pause > nul");
}
Сергей Долгих
Сергей Долгих
82 294
Лучший ответ