WRITE A C++ PROGRAM TO IMPLEMENT THE CONCEPT OF INDEX (Create index in text file) full code
C++ PROGRAM TO IMPLEMENT THE CONCEPT OF INDEX is provided below with the output screen:
// This header file includes every header file
#include<bits/stdc++.h>
using namespace std;
// Keeping the file name as documents
const string FILE_NAME = "documents.txt";
vector<string> File_Lines(string file)
{
ifstream in(FILE_NAME);
vector<string> lines;
for (string line; getline(in, line); )
{
lines.push_back(line);
}
return lines;
}
string get_input()
{
// Initializing string variable
string str;
getline(cin, str);
return str;
}
int main()
{
// reads the contents on line
vector<string> lines = File_Lines(FILE_NAME);
// open an output stream to append new lines
ofstream fileOut(FILE_NAME, ios::app);
long long t;
cout<<"Enter the number of line you want with index: "<<endl;
cin>>t;
for (int n = 0; n < t; n++)
{
// get a line from the user
cout << "> ";
std::string t = get_input();
// finding it in the vector of lines
auto it = std::find(lines.begin(), lines.end(), t);
if (it == lines.end())
{
// if the line was not found then append it
fileOut << t << endl;
lines.push_back(t);
cout << "Line \"" << t << "\" is indexed.\n";
}
else
{
// the line was found then this is the index.
int index = it - lines.begin();
cout << "Line \"" << t << "\" was found at index: " << index << ".\n";
// getting the adjacent line
int indexx;
if (index%2 == 0)
{
// if the index is even then get the next line
indexx = index + 1;
}
else
{
// odd index, get the previous line
indexx = index - 1;
}
if (indexx < lines.size())
{
string line2 = lines[indexx]; // the text of the adjacent line
cout << "Adjacent line: \"" << line2 << "\" (index " << indexx << ")\n";
}
else
{
cout << "No adjacent line is found yet!\n";
}
} // ends if the line was found
} // ends for t times
cout << endl;
get_input();
return 0;
}
Output screen:
Now the file named "Documents" will be created with the lines entered by the user indexed in it.
Thank you!!! Good luck! Keep Coding :)
Get Answers For Free
Most questions answered within 1 hours.