Connecting Tech Pros Worldwide Help | Site Map

find word in file

Member
 
Join Date: Oct 2006
Location: Australia
Posts: 38
#1: Dec 8 '06
Hi i have been trying to solve this question:

Write a C++ program to find a given word in a file. It should display all the line numbers where the word occurs.

i did this code:

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <conio.h>
  3. #include <fstream>
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. string s1;
  10. ifstream in ("file.txt");
  11. int lines = 0;
  12. cout << "Enter your search string: " <<endl;
  13. cin >> s1;
  14.  
  15. while(!in.eof())
  16. {
  17.    in.seekg(0,ios::beg);
  18.    lines ++;
  19.    if(//String in file)
  20.    {
  21.  
  22.    cout<<"The  string occured at lines: " << lines<<endl;
  23.   }
  24. }
  25.  
  26. in.close();
  27.  
  28. getch();
  29. return 0;
  30. }
i just have problems in interpreting this part to code:
if(//String in file), hope that someone can help me fix it.

thanks

carly
DemonPiggies's Avatar
Newbie
 
Join Date: Dec 2006
Location: Westerly, RI
Posts: 8
#2: Dec 8 '06

re: find word in file


this site has info about the ios::beg
http://www.cplusplus.com/doc/tutorial/files.html
it should be able to help you thru the search
I've used those funct.'s before so I can't really help without rewrite the program
but i'm assuming you need it to work with the one you posted right?
DemonPiggies's Avatar
Newbie
 
Join Date: Dec 2006
Location: Westerly, RI
Posts: 8
#3: Dec 8 '06

re: find word in file


it also covers the " in.seekg(0,ios::beg) "
which you'll probably use to read each line and then maybe dump it in to a string (which might be easier to compare) and compare sl ( the user's string) with each character in the file...
like if( sl[x] == (Character from File) )...
well something like that, just make sure you add so error coding tho...
Member
 
Join Date: Oct 2006
Location: Australia
Posts: 38
#4: Dec 8 '06

re: find word in file


Quote:

Originally Posted by DemonPiggies

this site has info about the ios::beg
http://www.cplusplus.com/doc/tutorial/files.html
it should be able to help you thru the search
I've used those funct.'s before so I can't really help without rewrite the program
but i'm assuming you need it to work with the one you posted right?

ummm... I only needed help in writing this part to code:
Expand|Select|Wrap|Line Numbers
  1. if(//String in file)
, the tutorials you gave me didnt really help me in figuring out how i can translate that sentence to code, but thanks anyway

carly
Reply