在文本文档中查找特定行

Find specific lines in text document

本文关键字:查找 文本 文档      更新时间:2023-10-16

我想创建一个小程序来更好地理解我需要的东西。

该代码可以将单词写入文本文档,按顺序在前一行下写入新行,并在重新启动程序后将行保留在那里。

现在,在向文件中添加一个新单词或短语之前,我想知道这个单词是否已经存在于我的文档中,如果存在,不要添加它,而是在输出时使exit等于一,从文件中读取它,这里的主要内容是在当前存在行的下方或上方找到行。例如:如果现有行索引为3,我希望看到+1行4或-1行2。如果文本文档中不存在新词,只需添加即可。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
std::ofstream outfile("doc.txt", std::ios_base::app); 
int main()
{
    std::string t;
    for (int i = 0; i < 10; i++)
    {
        cout << "Add new phrase: " << endl;
        std::getline(std::cin, t); 
        cout << t << endl;
        outfile << t << std::endl;
    }
    _getch();
    return 0;
}

编辑:

using namespace std;
std::ofstream outfile("doc.txt", std::ios_base::app);
int main()
{
    int length = 100;
    std::ifstream infile("doc.txt", std::ifstream::in);
    infile.seekg(0, infile.end);
    size_t len = infile.tellg();
    infile.seekg(0, infile.beg);
    char *buf = new char[len];
    infile.read(buf, length);
    infile.close();
    std::string writtenStr(reinterpret_cast<const char *>(buf), len);
    std::string t;
    for (int i = 0; i < 10; i++)
    {
        std::getline(std::cin, t);
        if (writtenStr.find(t) != std::string::npos)
        {
            cout << "Line [" << t << "] exist." << endl;
        }
        else
        {
            cout << "Line [" << t << "] saved." << endl;
            writtenStr += t;
            outfile << t << std::endl;
        }
    }
    _getch();
    return 0;
}

程序启动时,我会将文件读取为字符串。然后,每次我想添加一个新词时,都要检查这个短语的字符串。如果字符串中不包含短语,请将其添加到字符串和文件中,如果需要,还可以添加您选择的分隔符。例如:

int main()
{
    // Read existing file into a string
    std::ifstream infile("doc.txt", std::ifstream::in);
    infile.seekg(0, infile.end);
    size_t len = infile.tellg();
    infile.seekg(0, infile.beg);
    char *buf = new char[len];
    infile.read(buf,length);
    infile.close();
    std::string writtenStr(reinterpret_cast<const char *>(buf), len);
    // Open file for output
    std::ofstream outfile("doc.txt", std::ios_base::app); 
    std::string t;
    for (int i = 0; i < 10; i++)
    {
        // Get new phrase
        std::getline(std::cin, t); 
        // Check if phrase is already in file;
        if (writtenStr.find(t) == std::string::npos) 
        {
            cout << "Could not add new phrase: " << endl;
            cout << t << endl;
            cout << "Phrase already exists in file." << endl;
        } 
        else
        {
            cout << "Add new phrase: " << endl;
            cout << t << endl;
            writtenStr += t;
            outfile << t << std::endl;
        }
    }
    _getch();
    return 0;
}