Find a word in the text file

Hi
Can I use strcmp() to check the word/sentence in the text file?
If that word exist in the text,
it prints the message.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream> 
#include <fstream>
using namespace std;
int main()
{
char word[20];
cout << "Enter your word:\t";
cin >> word;

ifstream fin("myfile.txt");
if (strcmp(match, word) == 0)  //check the word
{
cout << "You find the word.\n";
fin.close();
}
else
cout<<"the word dont exist\n";
cout<<"please try again";
return 0;
}


Thank you
According to the following reference page it looks like you can:
http://www.cplusplus.com/reference/cstring/strcmp/?kw=strcmp

What's going on with this code? Are you having a compiler error or is this just if you want to know if it will work well (as in little overhead, etc.)?

I hope i can help you more.

- Hirokachi

But you do need to actually read the file before you preform the check.
Thank you Hirokachi and jlb

I want to find a word in the text file.
but I dont know how to write the code
How can I use the function strcmp()
to compare the word I input with the word in "myfile.text"?
And check the word is it exist or not in the text file

For example,
If "kelvin" "tom" are in "myfile.txt" ,
After I input kelvin,
the program prints the message "You find the word"

Last edited on
Here is a tutorial page that can help you write the code to get input from a file:
http://www.cplusplus.com/doc/tutorial/files/

I think that this page will help you tremendously.

Please take a look over it and if you have any questions let us know. :D
strcmp() tests to see if two strings match.

To find one string in a loner string, you can use strstr()
http://www.cplusplus.com/reference/cstring/strstr/

You might also consider using std::string, which provides string::compare()/operator== to do the same as strcmp and string::find() do do the same as strstr().
http://www.cplusplus.com/reference/string/string/

Andy
Last edited on
thank you
But I still have some questions about the use of strcmp().
Can I use the strcmp() to see if two strings match
while one is input by the user and the other one is in the text file?
If it is possible ,how can i perform it?
Topic archived. No new replies allowed.