С Новым годом! Форум программистов, компьютерный форум, киберфорум
C++
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.88/8: Рейтинг темы: голосов - 8, средняя оценка - 4.88
174 / 0 / 0
Регистрация: 10.09.2022
Сообщений: 304

Как заменить текст в txt файле

19.08.2023, 16:14. Показов 1783. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Есть txt файл из нескольких строк каждая из которых начинается с заглавной латинской буквы за которой идет пробел и какой то текст . Как заменить текст после буквы S а если нет строки начинающейся на S дописать в конец файла
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
19.08.2023, 16:14
Ответы с готовыми решениями:

Как найти и заменить текст в Memo или в txt-файле?
Как наити и заменить в мемо или в .txt фаиле текст? у меня есть .txt фаил... содержит очин длинний текст... как наити в нём конкретний...

Заменить определенный текст в файле .txt для всех файлов в выбранной папке
Есть код который меня это для одного указанного файла, как сделать чтобы менял для всех в определенной папке? const ForWriting = 2 ...

Работа с .txt файлами, как заставить richTextBox записывать, перезаписывать и читать текст в .txt файле
Всем доброго времени суток. Есть два текстовика, которые лежат в разных папках (условные folder\test1.txt и folder2\test2.txt), две...

3
113 / 115 / 19
Регистрация: 03.06.2022
Сообщений: 756
19.08.2023, 22:41
можно считать текст функцией file, далее каждый элемент массива проверить, является ли первая буква S
0
Эксперт функциональных языков программированияЭксперт С++
 Аватар для Royal_X
6142 / 2835 / 1040
Регистрация: 01.06.2021
Сообщений: 10,339
24.08.2023, 19:03
Лучший ответ Сообщение было отмечено Royal_X как решение

Решение

gdfgnggf, допустим наш текстовый файл называется file.txt и содержит такой текст:
A When the element type of an array is another array, it is said that the array is multidimensional.
W If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.
E The C++ numerics library includes common mathematical functions and types, as well as optimized numeric arrays and support for random number generation.
S The goto statement transfers control to the location specified by label.
O The Containers library is a generic collection of class templates and algorithms that allow programmers to easily implement common data structures like queues, lists and stacks.
M The storage of the vector is handled automatically, being expanded and contracted as needed.
E Namespace aliases allow the programmer to define an alternate name for a namespace.
S Virtual functions are member functions whose behavior can be overridden in derived classes.
L A function declaration introduces the function name and its type.
U At program termination, data written to files is exactly as if the program was executed as written.
T The stream-based input/output library is organized around abstract input/output devices.
Теперь предположим, что хотим заменить тексты после S и пробела на Hello world

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
 
int main()
{
    constexpr char file_name[]{"file.txt"};
    const std::string replacement{"Hello world"};
    std::fstream file(file_name, std::ios::in);
    if (!file.is_open())
    {
        std::cerr << "Unable to open the \"" << file_name << "\"\n";
        return 0;
    }
    std::string line;
    std::vector<std::string> lines;
    bool s = false;
    while (std::getline(file, line))
    {
        if (line.front() == 'S')
        {
            if (!s) s = true;
            lines.push_back("S " + replacement);
        }
        else lines.push_back(line);
    }
    file.close();
    if (!s) lines.push_back(replacement);
    file.open(file_name, std::ios::out);
    for (const auto &line : lines)
        file << line << std::endl;
    file.close();
    std::cout << "Done!" << std::endl;
}
Кстати, в коде также реализовано требование, что если нет строк, начинающихся на S, то добавить текст замены в конец файла.
Файл должен лежать в той же папке, что и исходник, либо нужно прописать его полный путь в названии.
0
11 / 6 / 7
Регистрация: 06.10.2016
Сообщений: 65
27.08.2023, 10:51
Config.h - конфиг программы, где можно указать локаль программы - RU или EN, файл-источник, файл-результат, текст для перестановки.

Translator - переводчик, где указываются строки переводов для RU и EN локалей.

Класс FileManager - менеджер работы с файлами

Класс ConsoleLogger - простой логгер для консоли

Класс LinesProcessor - обработчик строк в файле. Внутри него как раз происходят перестановки строк.


Текст взял от юзера выше, спасибо ему!) Royal_X

main.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "Config.h"
#include "FileManager.h"
#include "ConsoleLogger.h"
#include "LinesProcessor.h"
 
std::unique_ptr<ConsoleLogger> initializeLogger();
std::unique_ptr<FileManager> initializeFileManager(const std::unique_ptr<ConsoleLogger>& logger);
std::unique_ptr<LinesProcessor> initializeLinesProcessor(const std::unique_ptr<ConsoleLogger>& logger, const std::unique_ptr<FileManager>& fm);
 
int main()
{
    auto logger = initializeLogger();
    auto fileManager = initializeFileManager(logger);
    auto linesProcessor = initializeLinesProcessor(logger, fileManager);
    
    auto lines = fileManager->GetFileContent(FILE_FOR_PROCCESS);
    linesProcessor->Go(lines);
 
    fileManager->WriteContentToFile(lines, PROCESSED_FILE);
    
    return 0;
}
 
std::unique_ptr<ConsoleLogger> initializeLogger()
{
    std::vector<LoggerParam> loggerConfig = { };
    if (SYSTEM_LOCALE == RUSSIAN_LOCALE) {
        loggerConfig.push_back(LoggerParam::ENABLE_RUSSIAN_LANGUAGE);
    }
    
    std::unique_ptr<ConsoleLogger> logger = std::make_unique<ConsoleLogger>(loggerConfig);
    
    if (DEBUG_MODE) {
        logger->PrintMessage("logger_initialized", { PrintMsgParam::SPECIAL_MESSAGE });
    }
 
    return logger;
}
 
std::unique_ptr<FileManager> initializeFileManager(const std::unique_ptr<ConsoleLogger>& logger)
{
    std::unique_ptr fManager = std::make_unique<FileManager>(logger.get());
    if (DEBUG_MODE) {
        logger->PrintMessage("file_manager_initialized", { PrintMsgParam::SPECIAL_MESSAGE });
    }
 
    return fManager;
}
 
std::unique_ptr<LinesProcessor> initializeLinesProcessor(const std::unique_ptr<ConsoleLogger>& logger, const std::unique_ptr<FileManager>& fm)
{
    std::unique_ptr linesProcessor = std::make_unique<LinesProcessor>(logger.get());
    linesProcessor->SetFileManager(fm.get());
    if (DEBUG_MODE) {
        logger->PrintMessage("lines_processor_initialized", { PrintMsgParam::SPECIAL_MESSAGE });
    }
 
    return linesProcessor;
}
FileManager.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma once
#include "Config.h"
#include <iostream>
#include <vector>
#include "ConsoleLogger.h"
 
class FileManager
{
public:
    FileManager();
    FileManager(ConsoleLogger* logger);
    ~FileManager();
 
public:
    bool AssertFileExists(const std::string& filename, const bool& loggerAlarmRequired = false);
    bool IsFileEmpty(const std::string& filename, const bool& loggerAlarmRequired = false);
    std::vector<std::string> GetFileContent(const std::string& filename);
    void WriteContentToFile(std::vector<std::string>& lines, const std::string& filename);
 
private:
    ConsoleLogger* logger;
};
FileManager.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "FileManager.h"
#include <fstream>
#include <filesystem>
#include <sstream>
#include <string>
 
typedef ConsoleLogger::PrintMessageParams PrintMsgParam;
 
FileManager::FileManager()
{ }
 
FileManager::FileManager(ConsoleLogger* logger) 
    : logger(logger)
{ }
 
FileManager::~FileManager()
{ }
 
bool FileManager::AssertFileExists(const std::string& filename, const bool& loggerAlarmRequired)
{
    std::ifstream file(filename.c_str());
    
    bool fileExists = file.good();
 
    if (loggerAlarmRequired && logger) {
        logger->PrintMessage("[" + filename + "] - ", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK, PrintMsgParam::DONT_USE_TRANSLATOR });
 
        if (fileExists) {
            logger->PrintMessage("file_exists");
        } else {
            logger->PrintMessage("file_not_exists");
        }
    }
 
    file.close();
 
    return fileExists;
}
 
bool FileManager::IsFileEmpty(const std::string& filename, const bool& loggerAlarmRequired)
{
    if (!this->AssertFileExists(filename, loggerAlarmRequired)) {
        return true;
    }
 
    return this->GetFileContent(filename).empty();
}
 
std::vector<std::string> FileManager::GetFileContent(const std::string& filename)
{
    std::vector<std::string> readingResult;
    
    if (!this->AssertFileExists(filename, true)) {
        return readingResult;
    }
 
    std::ifstream file(filename);
    std::string line;
    while (std::getline(file, line)) {
        readingResult.push_back(line);
    }
 
    file.close();
 
    return readingResult;
}
 
void FileManager::WriteContentToFile(std::vector<std::string>& lines, const std::string& filename)
{
    std::ofstream file(filename, std::fstream::out);
 
    for (std::string& line : lines) {
        file << line << "\n";
    }
 
    this->logger->PrintMessage("new_data_writed_to_file", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK });
    this->logger->PrintMessage(" [" + filename + "]", {PrintMsgParam::DONT_USE_TRANSLATOR, PrintMsgParam::PAUSE_SCREEN });
 
    file.close();
}
ConsoleLogger.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "FileManager.h"
#include <fstream>
#include <filesystem>
#include <sstream>
#include <string>
 
typedef ConsoleLogger::PrintMessageParams PrintMsgParam;
 
FileManager::FileManager()
{ }
 
FileManager::FileManager(ConsoleLogger* logger) 
    : logger(logger)
{ }
 
FileManager::~FileManager()
{ }
 
bool FileManager::AssertFileExists(const std::string& filename, const bool& loggerAlarmRequired)
{
    std::ifstream file(filename.c_str());
    
    bool fileExists = file.good();
 
    if (loggerAlarmRequired && logger) {
        logger->PrintMessage("[" + filename + "] - ", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK, PrintMsgParam::DONT_USE_TRANSLATOR });
 
        if (fileExists) {
            logger->PrintMessage("file_exists");
        } else {
            logger->PrintMessage("file_not_exists");
        }
    }
 
    file.close();
 
    return fileExists;
}
 
bool FileManager::IsFileEmpty(const std::string& filename, const bool& loggerAlarmRequired)
{
    if (!this->AssertFileExists(filename, loggerAlarmRequired)) {
        return true;
    }
 
    return this->GetFileContent(filename).empty();
}
 
std::vector<std::string> FileManager::GetFileContent(const std::string& filename)
{
    std::vector<std::string> readingResult;
    
    if (!this->AssertFileExists(filename, true)) {
        return readingResult;
    }
 
    std::ifstream file(filename);
    std::string line;
    while (std::getline(file, line)) {
        readingResult.push_back(line);
    }
 
    file.close();
 
    return readingResult;
}
 
void FileManager::WriteContentToFile(std::vector<std::string>& lines, const std::string& filename)
{
    std::ofstream file(filename, std::fstream::out);
 
    for (std::string& line : lines) {
        file << line << "\n";
    }
 
    this->logger->PrintMessage("new_data_writed_to_file", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK });
    this->logger->PrintMessage(" [" + filename + "]", {PrintMsgParam::DONT_USE_TRANSLATOR, PrintMsgParam::PAUSE_SCREEN });
 
    file.close();
}
ConsoleLogger.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "ConsoleLogger.h"
#include <time.h>
 
ConsoleLogger::ConsoleLogger(const std::vector<ConsoleLoggerParams>& config)
    : initialConfig(config)
{ 
    this->Initialize();
}
 
void ConsoleLogger::Initialize()
{
    auto cfgBeginPtr = this->initialConfig.begin();
    auto cfgEndPtr = this->initialConfig.end();
 
    UINT codePage = this->US_CODE_PAGE;
    if (std::find(cfgBeginPtr, cfgEndPtr, ConsoleLoggerParams::ENABLE_RUSSIAN_LANGUAGE) != cfgEndPtr) {
        codePage = this->RUSSIAN_CODE_PAGE;
    }
 
    SetConsoleCodePage(codePage);
 
    this->translator.setLocale(codePage == this->RUSSIAN_CODE_PAGE ? "RU" : "EN");
}
 
void ConsoleLogger::PrintMessage(std::string message, const std::vector<PrintMessageParams>& params)
{
    auto paramsBeginPtr = params.begin();
    auto paramsEndPtr = params.end();
    auto AddEmptyLine{ []() {std::cout << std::endl; } };
 
    if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::CLEAR_SCREEN) != paramsEndPtr) {
        this->ClearScreen();
    }
    
    if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::EXTRA_LINE) != paramsEndPtr) {
        AddEmptyLine();
    }
    
    if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::SPECIAL_MESSAGE) != paramsEndPtr) {
        this->PrintTimestamp();
    }
 
    bool useTranslator = true;
    if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::DONT_USE_TRANSLATOR) != paramsEndPtr) {
        useTranslator = false;
    }
    
    if (useTranslator) {
        std::cout << translator.Translate(message);
    } else {
        std::cout << message;
    }
 
    if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::REMOVE_LINE_BREAK) == paramsEndPtr) {
        AddEmptyLine();
    }
    
    if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::EXTRA_LINE_AT_THE_END) != paramsEndPtr) {
        AddEmptyLine();
    }
    
    if (std::find(paramsBeginPtr, paramsEndPtr, PrintMessageParams::PAUSE_SCREEN) != paramsEndPtr) {
        this->PauseScreen();
    }
}
 
void ConsoleLogger::ClearScreen()
{
    system("CLS");
}
 
void ConsoleLogger::PauseScreen()
{
    system("pause");
}
 
void ConsoleLogger::SetConsoleCodePage(const UINT& codePage)
{
    SetConsoleCP(codePage);
    SetConsoleOutputCP(codePage);
}
 
void ConsoleLogger::PrintTimestamp()
{
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    localtime_s(&tstruct, &now);
    
    strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);
 
    std::string timestamp = { buf };
    std::cout<< "["<< timestamp <<"]: ";
}
 
ConsoleLogger::~ConsoleLogger()
{
}
LinesProcessor.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#pragma once
#include <vector>
#include <iostream>
#include "ConsoleLogger.h"
#include "FileManager.h"
#include <string>
 
class LinesProcessor
{
public:
    LinesProcessor(ConsoleLogger* logger);
    ~LinesProcessor();
 
public:
    void SetFileManager(FileManager* fManager);
    void Go(std::vector<std::string>& lines);
 
private:
    std::vector<int> GetNeededDataLinesIndexes(std::vector<std::string>& lines);
    std::string DoReplaceLine(const std::string& line);
    std::string GetLineForReplace();
 
private:
    ConsoleLogger* logger;
    FileManager* fm;
};
LinesProcessor.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "LinesProcessor.h"
 
LinesProcessor::LinesProcessor(ConsoleLogger* logger)
    : logger(logger)
{ }
 
LinesProcessor::~LinesProcessor()
{ }
 
void LinesProcessor::SetFileManager(FileManager* fManager)
{
    this->fm = fManager;
}
 
void LinesProcessor::Go(std::vector<std::string>& lines)
{
    if (lines.empty()) {
        return;
    }
 
    auto neededLinesIndexes = this->GetNeededDataLinesIndexes(lines);
    if (neededLinesIndexes.empty()) {
        lines.push_back(this->GetLineForReplace());
        this->logger->PrintMessage("template_line_added_to_file", { PrintMsgParam::SPECIAL_MESSAGE });
 
        return;
    }
    
    if (DEBUG_MODE) {
        this->logger->PrintMessage("data_replacing_started", { PrintMsgParam::SPECIAL_MESSAGE });
    }
 
    for (UINT lineIndex : neededLinesIndexes) {
        lines[lineIndex] = this->DoReplaceLine(lines[lineIndex]);
    }
 
    if (DEBUG_MODE) {
        this->logger->PrintMessage("data_replacing_finished", { PrintMsgParam::SPECIAL_MESSAGE });
    }
}
 
std::vector<int> LinesProcessor::GetNeededDataLinesIndexes(std::vector<std::string>& lines)
{
    std::vector<int> neededLinesIndexes;
    UINT iterator = 0;
 
    this->logger->PrintMessage("needed_data_searching_started", { PrintMsgParam::SPECIAL_MESSAGE });
    for (std::string& line : lines) {
        if (line[0] == 'S' && line[1] == ' ') {
            if (DEBUG_MODE) {
                this->logger->PrintMessage("needed_data_found_at", { PrintMsgParam::SPECIAL_MESSAGE, PrintMsgParam::REMOVE_LINE_BREAK });
                this->logger->PrintMessage(std::to_string(iterator), { PrintMsgParam::DONT_USE_TRANSLATOR });
            }
            
            neededLinesIndexes.push_back(iterator);
        }
 
        iterator++;
    }
 
    if (neededLinesIndexes.empty()) {
        this->logger->PrintMessage("no_needed_data_was_detected_in_file", { PrintMsgParam::SPECIAL_MESSAGE });
    } else {
        this->logger->PrintMessage("needed_data_searching_ended", { PrintMsgParam::SPECIAL_MESSAGE });
    }
 
    return neededLinesIndexes;
}
 
std::string LinesProcessor::DoReplaceLine(const std::string& line)
{
    std::string result = line;
    result.replace(result.begin() + 2, result.end(), NEW_TEXT.c_str());
 
    return result;
}
 
std::string LinesProcessor::GetLineForReplace()
{
    return "S " + NEW_TEXT;
}
Translator.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#pragma once
#include <iostream>
#include <vector>
 
class Translator {
public:
    Translator(const std::string& locale = "RU")
        : locale(locale)
    { }
 
public:
    std::string Translate(const std::string& msg) {
        std::vector<std::pair<std::string, std::string>>* dictionary = locale == "RU" ? &this->ruDictionary : &this->enDictionary;
 
        auto beginIterator = dictionary->begin();
        auto endIterator = dictionary->end();
        auto msgIterator = std::find_if(beginIterator, endIterator, [&msg](const std::pair<std::string, std::string>& element) {
            return element.first == msg; 
        });
 
        try {
            if (msgIterator != endIterator) {
                return msgIterator->second;
            }
        }
        catch (...) {
            return msg;
        }
 
        return msg;
    }
 
    void setLocale(const std::string& locale) noexcept{ this->locale = locale; }
 
private:
    std::string locale;
 
    std::vector<std::pair<std::string, std::string>> enDictionary = {
        std::make_pair<std::string, std::string>(
            "logger_initialized", "Logger successfully initialized"
        ),
        std::make_pair<std::string, std::string>(
            "file_manager_initialized", "File manager successfully initialized"
        ),
        std::make_pair<std::string, std::string>(
            "file_not_exists", "Current file doesn't exists"
        ),
        std::make_pair<std::string, std::string>(
            "file_exists", "Current file exists"
        ),
        std::make_pair<std::string, std::string>(
            "lines_processor_initialized", "Lines processor successfuly initialized"
        ),
        std::make_pair<std::string, std::string>(
            "no_needed_data_was_detected_in_file", "No needed data was detected in the file"
        ),
        std::make_pair<std::string, std::string>(
            "needed_data_searching_started", "Needed data searching started"
        ),
        std::make_pair<std::string, std::string>(
            "needed_data_found_at", "Needed data found at row with index: "
        ),
        std::make_pair<std::string, std::string>(
            "needed_data_searching_ended", "Needed data searching ended"
        ),
        std::make_pair<std::string, std::string>(
            "data_replacing_started", "Data replacing process has been started"
        ),
        std::make_pair<std::string, std::string>(
            "data_replacing_finished", "Data replacing process has been successfully finished"
        ),
        std::make_pair<std::string, std::string>(
            "new_data_writed_to_file", "New data has been successfully written to the file"
        ),
        std::make_pair<std::string, std::string>(
            "template_line_added_to_file", "Template line has been successfully added to file"
        )
    };
    
    std::vector<std::pair<std::string, std::string>> ruDictionary = {
        std::make_pair<std::string, std::string>(
            "logger_initialized", "Логгер успешно инициализирован"
        ),
        std::make_pair<std::string, std::string>(
            "file_manager_initialized", "Файловый менеджер успешно инициализирован"
        ),
        std::make_pair<std::string, std::string>(
            "file_not_exists", "Данный файл не существует"
        ),
        std::make_pair<std::string, std::string>(
            "file_exists", "Данный файл существует"
        ),
        std::make_pair<std::string, std::string>(
            "lines_processor_initialized", "Обработчик строк успешно инициализирован"
        ),
        std::make_pair<std::string, std::string>(
            "no_needed_data_was_detected_in_file", "Нужной информации не было найдено в файле"
        ),
        std::make_pair<std::string, std::string>(
            "needed_data_searching_started", "Поиск нужной информации начат"
        ),
        std::make_pair<std::string, std::string>(
            "needed_data_found_at", "Нужная информация была найдена в строке под номером: "
        ),
        std::make_pair<std::string, std::string>(
            "needed_data_searching_ended", "Поиск нужной информации завершён"
        ),
        std::make_pair<std::string, std::string>(
            "data_replacing_started", "Процесс перестановки информации в строках начат"
        ),
        std::make_pair<std::string, std::string>(
            "data_replacing_finished", "Процесс перестановки информации в строках успешно закончен"
        ),
        std::make_pair<std::string, std::string>(
            "new_data_writed_to_file", "Новая информация была успешно записана в файл"
        ),
        std::make_pair<std::string, std::string>(
            "template_line_added_to_file", "Шаблонная строка была успешно добавлена в файл"
        )
    };
};
Config.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#pragma once
#include <iostream>
#include "ConsoleLogger.h"
 
typedef ConsoleLogger::PrintMessageParams PrintMsgParam;
typedef ConsoleLogger::ConsoleLoggerParams LoggerParam;
 
const std::string RUSSIAN_LOCALE = "RU";
const std::string ENGLISH_LOCALE = "EN";
 
const std::string SYSTEM_LOCALE = RUSSIAN_LOCALE;
 
const std::string FILE_FOR_PROCCESS = "source.txt";
const std::string PROCESSED_FILE = "output.txt";
const std::string NEW_TEXT = "my new replaced text";
 
const bool DEBUG_MODE = true;
Вложения
Тип файла: rar Project.rar (1.56 Мб, 2 просмотров)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
27.08.2023, 10:51
Помогаю со студенческими работами здесь

Как изменить текст в файле .txt?
Private Sub Form_Load() If Dir$(&quot;C:\tmp\amd.txt&quot;, vbNormal) = &quot;&quot; Then Dim f As Integer f = FreeFile Open &quot;C:\tmp&quot; &amp; &quot;\amd.txt&quot; For...

Как выровнять текст в txt файле по центру?
Имеется текстовый файл: qw ert yui, op asd. fg hjk 1 z xcv. bbb nnn mmm.

Найти и заменить слово в txt файле (как в блокноте)
Наити и заменить слово в txt файле (как в блокноте) Помогите реализовать (у самого очень мало опыта). :cry: Или хотя бы куда копать....

Нужно заменить строку в файле text.txt словами из другого файла words.txt
Допустим в файле words.txt есть какие-то слова ,например : #один,#два,#три. И есть файл text.txt,где есть слова: один,два,три,четыре,пять...

Как заменить текст в файле
Такая проблема. Программа считывает текстовый файл, считывается каждое слово. Далее это слово проходит проверку под условие. Если оно эту...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Учёным и волонтёрам проекта «Einstein@home» удалось обнаружить четыре гамма-лучевых пульсара в джете Млечного Пути
Programma_Boinc 01.01.2026
Учёным и волонтёрам проекта «Einstein@home» удалось обнаружить четыре гамма-лучевых пульсара в джете Млечного Пути Сочетание глобально распределённой вычислительной мощности и инновационных. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru