Thread: searching a ifstream for a string

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    85

    searching a ifstream for a string

    i have this code...but i'm not sure why it isn't working, when i pick a string to search for i alway sget a really high number like 15 - 30 even though there probobly isn't more than 1 or 2 cases where string exists in the file.

    Code:
    void searchstring(ifstream& in, string search)
    
    {
      string word; 
      int count=0;
      while (!in.eof())
        {
          in >> word;
          if (word.find(search))
            count++;
        }
      cout << "# of Search String  "<<search<<"  : " << count << endl;
    }
    the file i'm searching has the word "Jill" in it twice and when i search for it i get back 29...
    any ideas?

  2. #2
    aoeuhtns
    Join Date
    Jul 2005
    Posts
    581
    You probably want to use string::npos != word.find(search), because look how http://cppreference.com/cppstring/find.html works.
    There are 10 types of people in this world, those who cringed when reading the beginning of this sentence and those who salivated to how superior they are for understanding something as simple as binary.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    85
    oh, that worked, thanks!

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If "Jillian" is supposed to match "Jill" (and "JJill is supposed match "Jill") then using find is fine (with Rashakil Fol's suggested change). Otherwise you should just compare with == instead of find so that "Jill" only matches "Jill".

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM