John K John K - 1 year ago 81
C++ Question

C++ line index in text document

as beginner need your help

So I'm trying to make program which can write phrases into the text document, new line below previous, just in original order. It checks If phrase exist in document and shows me the row on output, if not, add it as new.

Now I want two thing here, and can't figure out, question is how to get index for lines, and how to manipulate with it to get lines, for example my text document content:


Now, if text inserted by user for example "word6", which is not exist in document, just must be added below. But if inserted text for example "word1" which is exist in document, in this case I want see on output "word2", which is below the found "word1", but if inserted text is "word2", I want see on output "word1" etc. if "word3" on output show me "word4", if "word4" show me "word3" etc, depending which index has been defined in current exist word, divisible -1 or not divisible +1 like this:

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];, length);
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;
cout << "Line [" << t << "] saved." << endl;
writtenStr += t;
outfile << t << std::endl;
return 0;

qxz qxz
Answer Source

First of all, an easy way to read an entire file into an std::string (ref):

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

But, if you want to get a list (std::vector) of lines, try this instead:

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

lines will then contain a list of each line in the file. If you want to find the index of a particular line in this list (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();

Once you have the index of a line, you can get the adjacent line described in your question like this:

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

Other tips:

Your std::ofstream should probably be a local variable. Declare it inside of your int main().

ifstreams get the std::ios::in flag by default, so you can leave out that second parameter to its constructor.

If you dynamically allocate memory (with new type or new type[len]), always make sure it gets freed (with delete or delete[]). Example from your code:

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

Complete working example:

#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); ) {
    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;
    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download