Having a hard time understanding EOF-Controlled while loops c++ my incomplete co
ID: 3831459 • Letter: H
Question
Having a hard time understanding EOF-Controlled while loops c++
my incomplete code
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string word; // The word entered by the user
string result; // The word read from the file
int counter = 0; // Counts the number of lines read from the file
bool found = false; // If the user's word has been found
ifstream inFile; // The input file
//open the dictionary file.
inFile.open("dictionary.txt");
//ask the user to input the word they want to search for.
cout << "Enter a word to search on dictionary: " << endl;
cin >> word;
// Use a while loop to loop through the file.
// Use break to stop the loop if the word is found
while (!inFile.eof()) {
}
// If the word is not found display a message.
For your program you will search a dictionary file for the word provided by the user. First ask the user to input a word. Search the dictionary file for that word and tell the user whether or not the word was found.
This program demonstrates the linear search technique. When you perform a linear search, you start at the beginning of a list and search through the list in order until you reach the desired item or the end of the list (Hint - use break to stop the program when you find the desired item).
Use the provided dictionary file for Windows dictionary.txt
expected output
Explanation / Answer
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string word; // The word entered by the user
string result; // The word read from the file
int counter = 0; // Counts the number of lines read from the file
bool found = false; // If the user's word has been found
ifstream inFile; // The input file
//open the dictionary file.
inFile.open("dictionary.txt");
//ask the user to input the word they want to search for.
cout << "Enter a word to search on dictionary: " << endl;
cin >> word;
// Use a while loop to loop through the file.
// Use break to stop the loop if the word is found
while (!inFile.eof()) {
inFile >> result ;
counter++;
if(result == word){
found = true;
break;
}
}
if(!found){
cout<<"The word is not found"<<endl;
}
else{
cout<<"The word is found at "<<counter<<endl;
}
inFile.close();
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter a word to search on dictionary:
bye
The word is found at 8
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter a word to search on dictionary:
sure
The word is not found
dictionary.txt
Hi
good morning
hw are you
say bye
thank you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.