C++ Task on Searching and Sorting Project

C++ Task on Searching and Sorting Project

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

vector<string> split(string str, string delimiter) {
vector<string>result;
while (str.size()) {
int index = str.find(delimiter);
if (index != string::npos) {
result.push_back(str.substr(0, index));
str = str.substr(index + delimiter.size());
if (str.size() == 0)result.push_back(str);
}
else {
result.push_back(str);
str = “”;
}
}
return result;
}

int main()
{
string file = “words.txt”;
vector<string> word;
fstream newfile;
newfile.open(file, ios::in); //open a file to perform read operation using file object
if (newfile.is_open())
{ //checking whether the file is open
string str;

string delimiter = ” “;
while (getline(newfile, str)) //read data from file object and put it into vector.
{
vector<string> temp;
temp = split(str,” “);
for (int i = 0; i < temp.size(); i++)
{
word.push_back(temp[i]);
}

}
newfile.close();

string temp;
// sorting the word in ascending order in stored in vector using bubble sort
for (int i = 0; i < word.size() – 1; ++i)
for (int j = i + 1; j < word.size(); ++j)
{
if (word[i] > word[j])
{
temp = word[i];
word[i] = word[j];
word[j] = temp;
}
}

cout << “Enter the Word You Want To Search” << endl;
string searchWord;
cin >> searchWord;
// binary search

int flag = 0;
int length = searchWord.length();

string before = searchWord;
before[length – 1] -= 1;

string after = searchWord;
after[length – 1] += 1;
for (int j = 0; j < word.size(); j++)
{
if (word[j].compare(searchWord) == 0)
{
cout << “Word found Original Word ” << searchWord << endl;
flag++;
}
if (word[j].compare(after) == 0)
{
cout << “Word found Original Word ” << searchWord << ” After Word ” << after << endl;;
flag++;
}

if (word[j].compare(before) == 0)
{
cout << “Word found Original Word ” << searchWord << ” Before Word ” << before << endl;
flag++;
}

}
if (flag == 0)
{
cout << “Word not found ” << endl;
}
}

return 0;
}