Top.Mail.Ru
Ответы
Аватар пользователя
7мес
Изменено
Аватар пользователя
Аватар пользователя
Аватар пользователя
Программирование
+3

Помогите написать программу С++

Найти самую короткую строку текста и заменить её фразой «С
новым годом!», учитывая, что исходная информация хранится в текстовом
файле.
Объясните пожалуйста код

По дате
По рейтингу
Аватар пользователя
Новичок
7мес
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
 #include <algorithm> 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector>

using namespace std;

struct Record { 
    string line; 
private: 
    friend istream& operator>>(istream& inp, Record& record) { 
        getline(inp, record.line); 
        return inp; 
    } 
    friend ostream& operator<<(ostream& out, const Record& record) { 
        return out << record.line; 
    } 
    friend bool operator<(const Record& a, const Record& b) { 
        return a.line.length() < b.line.length(); 
    } 
};

vector<Record> load(const string& path) { 
    vector<Record> records; 
    ifstream inp(path); 
    if (inp.is_open()) { 
        Record record; 
        while (inp >> record) records.push_back(record); 
        inp.close(); 
    } 
    return records; 
}

bool save(const string& path, const vector<Record>& records) { 
    ofstream out(path); 
    if (!out.is_open()) return false; 
    for (const auto& record : records) out << record << '\n'; 
    return true; 
}

int main() { 
    const string happy_new_year{ "С Новым годом!" }; 
    string path; 
    cout << "Путь к файлу: "; 
    getline(cin, path); 
    auto content = load(path); 
    min_element(begin(content), end(content))->line = happy_new_year; 
    puts(save(path, content) ? "Success" : "Failure");
    cin.get();
} 

P.S. А с кодировками разбирайтесь самостоятельно.

Аватар пользователя
Мастер
7мес

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <limits> // Для numeric_limits

using namespace std;

int main() {
// 1. Открываем файл для чтения
ifstream inputFile("input.txt"); // Замените "input.txt" на имя вашего файла

// Проверка, удалось ли открыть файл
if (!inputFile.is_open()) {
cerr << "Ошибка открытия файла!" << endl;
return 1; // Возвращаем код ошибки
}

// 2. Читаем строки из файла и сохраняем их в векторе
vector<string> lines;
string line;
while (getline(inputFile, line)) {
lines.push_back(line);
}

// Закрываем файл, он нам больше не нужен для чтения
inputFile.close();

// 3. Находим индекс самой короткой строки
int shortestLineIndex = -1;
int shortestLineLength = numeric_limits<int>::max(); // Инициализируем максимальным значением

for (int i = 0; i < lines.size(); ++i) {
if (lines[i].length() < shortestLineLength) {
shortestLineLength = lines[i].length();
shortestLineIndex = i;
}
}

// 4. Заменяем самую короткую строку на "С новым годом!"
if (shortestLineIndex != -1) {
lines[shortestLineIndex] = "С новым годом!";
} else {
cerr << "Файл пуст!" << endl;
return 1;
}

// 5. Открываем файл для записи (перезаписываем содержимое)
ofstream outputFile("input.txt"); // Открываем тот же файл для записи

// Проверка, удалось ли открыть файл
if (!outputFile.is_open()) {
cerr << "Ошибка открытия файла для записи!" << endl;
return 1;
}

// 6. Записываем измененные строки обратно в файл
for (const string& l : lines) {
outputFile << l << endl;
}

// Закрываем файл
outputFile.close();

cout << "Самая короткая строка заменена успешно!" << endl;

return 0;
}