文本文档中的C ++行索引

时间:2016-08-04 23:11:13

标签: c++

初学者需要你的帮助

因此,我正在尝试制作可以将短语写入文本文档的程序,以前的新行,只是按原始顺序编写。它检查文档中是否存在短语并显示输出中的行,如果不存在,则将其添加为新行。

现在我想在这里做两件事,并且想不通,问题是如何获取行的索引,以及如何使用它来获取行,例如我的文本文档内容:

word1
word2
word3
word4
word5

现在,如果用户插入的文本例如“word6”(文档中不存在),则必须在下面添加。但是如果插入文本例如“word1”存在于文档中,在这种情况下我想看输出“word2”,它位于找到的“word1”之下,但如果插入的文本是“word2”,我想看输出“word1”等,如果输出中的“word3”显示“word4”,如果“word4”显示“word3”等,则根据当前存在的字中定义的索引,可分为-1或不可分割+1,如下所示:

word1 (indivisible) show word2
word2 (divisible) show word1
word3 (indivisible) show word4
word4 (divisible) show word3
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;
}

1 个答案:

答案 0 :(得分:2)

首先,一种将整个文件读入std::stringref)的简便方法:

std::ifstream infile("file.txt");
std::string str(std::istreambuf_iterator<char>(t),
                std::istreambuf_iterator<char>());

但是,如果你想得到一个列表(std::vector),请尝试这样做:

std::ifstream infile("file.txt");
std::vector<std::string> lines;
for (std::string line; std::getline(infile, line); ) {
   lines.push_back(line);
}
然后

lines将包含文件中每行的列表。如果要在此列表中找到特定行的索引(ref):

std::string t = ...; // the line to search for
auto it = std::find(lines.begin(), lines.end(), t);
if (it == lines.end()) {
  // line wasn't found
} else {
  int index = it - lines.begin();
  //...
}

获得一行的索引后,您可以获得问题中描述的相邻行:

int index2;
if (index%2 == 0) {
  // even index
  index2 = index + 1;
} else {
  // odd index
  index2 = index - 1;
}
std::string str2 = lines[index2]; // the text of the adjacent line

其他提示:

你的std::ofstream应该是一个局部变量。在int main()

中声明它

ifstream默认情况下获取std::ios::in标志,因此您可以将第二个参数留给其构造函数。

如果你动态分配内存(new typenew type[len]),总是确保它被释放(使用deletedelete[]) 。代码中的示例:

char *buf = new char[len]; // dynamically allocated with new
// use buf somehow...
// when done with buf:
delete[] buf; // frees the memory

完成工作示例:

#include <fstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;


const string FILE_NAME = "doc.txt";

vector<string> getFileLines(string file) {
    ifstream in(FILE_NAME);
    vector<string> lines;
    for (string line; getline(in, line); ) {
        lines.push_back(line);
    }
    return lines;
}

string getUserInput() {
    string str;
    getline(cin, str);
    return str;
}

int main() {
    // read the contents of the text file into an std::vector of lines
    vector<string> lines = getFileLines(FILE_NAME);

    // open an output stream to append new lines
    ofstream fileOut(FILE_NAME, ios::app);

    // 10 times...
    for (int n = 0; n < 10; n++) {
        // get a line from the user
        cout << "> ";
        std::string t = getUserInput();

        // find it in the vector of lines
        auto it = std::find(lines.begin(), lines.end(), t); // "auto" deduces the type automatically
        if (it == lines.end()) {
            // the line wasn't found; append it...
            fileOut << t << endl; // to the file
            lines.push_back(t);   // to our cached list of lines
            cout << "Line \"" << t << "\" saved.\n";
        } else {
            // the line was found, and this is its index:
            int index = it - lines.begin();
            cout << "Line \"" << t << "\" found, at index " << index << ".\n";

            // get the adjacent line
            int index2;
            if (index%2 == 0) {
                // even index, get the next line
                index2 = index + 1;
            } else {
                // odd index, get the previous line
                index2 = index - 1;
            }
            if (index2 < lines.size()) {
                string line2 = lines[index2]; // the text of the adjacent line
                cout << "Adjacent line: \"" << line2 << "\" (index " << index2 << ")\n";
            } else {
                cout << "No adjacent line yet!\n";
            }
        } // end if (line was found)
    } // end for (10 times)

    cout << endl;
    getUserInput();
    return 0;
}