Word search

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){

string wordForQuery;

cout<<"Enter a word to be searched in the file words.txt:";
cin>>wordForQuery;

ifstream inFile;
inFile.open("words.txt");

string word;

while (inFile){
inFile >> word;

if (word == wordForQuery){
cout << "Found!"<<endl;
if (wordForQuery != word){
cout << "Not Found!" <<endl;
}
}

}
system("pause");
return 0;
}


======words.txt==============
there are some words in this file
that can be searched
==========================


Two things I need help with one is how do I make it so that if I type in searched for user input it wont display Found! twice but only once and second thing is how do I make the program instead displaying nothing when word can't be found to displaying "not Found!"

THANK YOU FOR HELP IN ADVANCE!!
You could explore a different direction and use the standard function find()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <algorithm>

using namespace std;

int main() {
    cout<<"Enter a word to be searched in the file words.txt:";
    string wordForQuery;
    cin>>wordForQuery;
    ifstream inFile("words.txt");
    istream_iterator<string> beg(inFile), end;
    if(find(beg, end, wordForQuery) != end)
        cout << "Found!\n";
    else
        cout << "Not Found!\n";
}

demo: http://ideone.com/qYXVd
Last edited on
Well the question said not to change the conditions of loop in anyway
I think you can do something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool found = false;
while (inFile && (!found)) {
    inFile >> word;
    
    if (word == wordForQuery) {
       found = true;
    }
}

if(!found) {
    cout << "Not Found!" << endl;
} else {
    cout << "Found!" << endl;
}
Last edited on
Thank You that worked perfectly I needed a boolean that is what it was ok
you're welcome =)
Topic archived. No new replies allowed.