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

该代码可以按顺序将单词写到文本文件中,在上一行下一行,并在重新启动程序后将行保留在该行中。

现在,在向文件中添加新单词或短语之前,我想查找文档中是否已存在该单词,如果存在,则不添加它,但在输出中获得一个存在的单词,从文件中读取它,然后主要在某种程度上,这也是找到当前存在的线以下或上方的线。例如:如果存在行索引为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;
}

10-06 12:16