Answers
#include<iostream>
#include<fstream>
#include <bits/stdc++.h>
using namespace std;
int findWord(string arr[], int MAX_SIZE, string word)
{
// Iterate over array
// if current word is equal to target
// return index
for(int i =0; i<MAX_SIZE; i++)
{
if(arr[i]==word)
{
return i;
}
}
// return -1 means word was not found
return -1;
}
int main()
{
// I have defined this 2, you can change it later
int const MAX_SIZE = 20;
fstream fileIn;
string filename = "dictionary.txt";
// Open file to read
fileIn.open(filename.c_str());
// Check if file exists
if(!fileIn)
{
cout<<"File cannot be opened!"<<endl;
return 0;
}
// Create an array of size MAX_SIZE
string arr[MAX_SIZE];
// index variable for array indexing
int index = 0;
string word = "";
// Iterate loop till the last word
while(fileIn>>word)
{
// add word to array
// increment index by 1
arr[index] = word;
index++;
}
string w;
// Ask user to enter a word to search
cout<<"Enter the word to find (-1 to exit): ";
cin>>w;
// Iterate a loop till user doesn't enter -1
while(w!="-1")
{
// call function to find word
// if position is -1, means word does not exists
// else print the location of word
int position = findWord(arr,MAX_SIZE,w);
if(position==-1)
{
cout<<"The word "<<w<<" doesn't exist in file"<<endl;
}
else
{
cout<<"The word "<<w<<" is in the file at position "<<(position+1)<<endl;
}
cout<<"Enter the word to find (-1 to exit): ";
cin>>w;
}
return 0;
}
INPUT FILE I USED
amateur
life
soul
sole
math
science
therapy
abacus
mine
toll
love
hate
abuse
marry
lenses
pair
fair
fare
mature
mint
OUTPUT-