1 answer

This lab will combine reading data from a file and searching the array to find a...

Question:

This lab will combine reading data from a file and searching the array to find a specific value.

Assignment

Write a program that reads in a file full of strings into an array, and prompts the user for a string to find in the array. The program should loop until a sentinel value (such as -1) is entered.

After looping in main() for the input, write a search function, with the following prototype:

int findWord(string [], int, string);

with arguments as follows:

1) The first argument, a string[] (array), is list of words read from the file.

2) The second argument, an 'int', is the maximum size of the file (define a constant such as MAX_SIZE in main(), not as a global variable, and pass it into this function here).

3) The third argument, a 'string', is requested word to be found.

The return 'int' should be the position in the array where the word appears (starting with 0 for the first word) or the value -1 if the word is not present in the array.

The input file is a list of dictionary words -- dictionary.txtPreview the document -- which you can find in this week's module.

How to Search

In your findWord function, use the linear search algorithm, which starts at the beginning of the array and then steps through the elements sequentially until either the desired value is found or the end of the array is reached.

For example, if the array is:

{ "hello", "goodbye", "sometimes", "never" }

and we want to find the word "sometimes", the algorithm would check each element, starting with "hello", to see if it is equal to the search key. When the search reaches either the found word or the end of the array, the algorithm stops.

Example Output

Enter the word to find (-1 to exit): abacus The word "abacus" is in the file at position 8884. Enter the word to find (-1 to exit): life The word "life" is in the file at position 1. Enter the word to find (-1 to exit): -1

What to Submit

Upload your main.cpp file (source code for your solution) and a screenshot of a single run with at least two lookups and an exit (i.e. entering '-1) to stop the program.

PreviousNext


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-

E:Practice\Chegglbin\Release\ Chegg.exe Enter the word to find (-1 to exit): abacus e word abacus is in the file at position

.

Similar Solved Questions

1 answer
Percent yield of chemical reactions Aqueous hydrobromic acid (HBr) reacts with solid sodium hydroxide (NaOH) to...
Percent yield of chemical reactions Aqueous hydrobromic acid (HBr) reacts with solid sodium hydroxide (NaOH) to produce aqueous sodium bromide (NaBr) and liquid water (HO). 189.71 g of water is produced from the reaction of 79.3 g of hydrobromic acid and 70.2 g of sodium hydroxide, calculate the per...
1 answer
QUESTION 21 If a monopoly situation arises from a perfectly competitive market, the portion of producer...
QUESTION 21 If a monopoly situation arises from a perfectly competitive market, the portion of producer surplus that increases in a monopoly is transferred from the perfectly competitive market's deadweight loss o fixed cost. consumer surplus. long-run positive economic profit. QUESTION 22 If a ...
1 answer
12-B12 This car is driving up the hill shown. When he passes the origin he is...
12-B12 This car is driving up the hill shown. When he passes the origin he is travelling 35 m/s and thereafter his x velocity is defined as Vx=35-1.2t. At t=15 seconds, determine The position (x,y) and the x,y components of both velocity and acceleration. • What does his speedometer read at tha...
1 answer
How is net income connected to retained earnings and how does the Statement of Retained Earnings...
How is net income connected to retained earnings and how does the Statement of Retained Earnings help the reader of financial statements understand a company’s past performance? What could you conclude about a company who ended their 3rd year of operations with a Net Loss of $20,000 but that h...
1 answer
Organic Fresh makes organic yogurt. The only ingredients, mik and bacteria cultures are added at the...
Organic Fresh makes organic yogurt. The only ingredients, mik and bacteria cultures are added at the very beginning of the fermentation process At month end. Organic Fresh has 140.000 cups of yogurt that are only 10% of the way through the fermentation process. Use the equivalent unit formula tower ...
1 answer
Calculate the pH of a 0.496 M aqueous solution of benzoic acid (C6H5COOH, Ka = 6.3×10-5)...
Calculate the pH of a 0.496 M aqueous solution of benzoic acid (C6H5COOH, Ka = 6.3×10-5) and the equilibrium concentrations of the weak acid and its conjugate base. pH = _____ [C6H5COOH ]equilibrium = _____M [C6H5COO- ]equilibrium = _____M...
1 answer
3. A fixed quantity of gas at 21 ∘C exhibits a pressure of 740 torr and...
3. A fixed quantity of gas at 21 ∘C exhibits a pressure of 740 torr and occupies a volume of 4.44 L. a. Use Boyle's law to calculate the volume the gas will occupy if the pressure is increased to 1.85 atm while the temperature is held constant. b. Use Charles's law to calculate the vol...
1 answer
Why is hydrogen not a metalloid?
Why is hydrogen not a metalloid?...
1 answer
Advanced methods of trigonometry can be used to find the exact value.
Advanced methods of trigonometry can be used to find the exact value....
1 answer
For each of the following four techniques, can an application be designed to communicate between ...
For each of the following four techniques, can an application be designed to communicate between more than one program file? Explain your answer. (a) shared memory (b) unnamed pipe (c) socket (d) multithreading Briefly explain at least one significant advantage for each of the four communication te...
1 answer
LESSUI 9.3 Problem 9.19 Part D Determine the equivalent state of stress on an element at...
LESSUI 9.3 Problem 9.19 Part D Determine the equivalent state of stress on an element at the same point which represents the principal stress, and the maximum in-plane shear stress and the associated average normal stress. Also, for each case, determine the corresponding orientation of the element w...
1 answer
The somnologist at the sleep clinic cannot tell from the EEG pattern if you are in...
The somnologist at the sleep clinic cannot tell from the EEG pattern if you are in REM or awake. She must rely on: Please choose one! Thank you. A) high frequency electrical activity of the brain B) sleep spindles C) eyes moving in circles D) the recordings of muscle tone...
1 answer
Which of the following has the largest third ionization energy? Ti, V, Cr, Sc, Ca
Which of the following has the largest third ionization energy? Ti, V, Cr, Sc, Ca...
1 answer
It is found experimentally that a compound composed only of iron and chlorine. A sample of...
It is found experimentally that a compound composed only of iron and chlorine. A sample of this compound is composed of 2.470 g of iron and 4.703 g of chlorine. What is the empirical formula for this compound? (3 points)...
1 answer
For five of the oligosaccharides, containing molecules or rides describe the oligosaccharide makeup, the type(s) and...
For five of the oligosaccharides, containing molecules or rides describe the oligosaccharide makeup, the type(s) and orientation of the saccharine and how that is made possible by the composition and structure of the saccharine. a) cellulose b) chitin c) amyl pectin d) hyaluronic acid g) glycosamino...
1 answer
Please use the 2019 tax system Cross Income Exclusions and Deductions for AGI 4–39 13. Physical...
please use the 2019 tax system Cross Income Exclusions and Deductions for AGI 4–39 13. Physical Injury and Sickness Payments. (Obj. 1) For each taxpayer, discuss how much (if any) of the payments received during the year are included in gross income. a. Anne sued her employer for discriminatio...
1 answer
What other aspects of life can lead to vulnerabilities in attaining adequate nutrition? How?
What other aspects of life can lead to vulnerabilities in attaining adequate nutrition? How?...