Thread: reading from file

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    20

    reading from file

    hi,
    Does anyone know of a way to search a file for certain records and also the record right after the last record you were looking for? k...that probably makes no sense!!

    e.g
    I want to go through a file like this
    dog,1,...
    dog,2,...
    dog,3,...
    cat,2,...
    cat,3,...
    cat,4,...
    so if I was searching for dog, my output should be something like this
    dog,1,...
    dog,2,...
    dog,3,...
    cat,2,...

    Thanks,
    Kings

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Use getline() to read a line (assuming there is only one entry per line) then make a comparer that compares the first 'word' (the characters until a space or, in your case, a comma is found) with whatever you're searching for. Simply using strcmp() is not good since it will compare the whole line. I guess there are some token comparers available, but none that I know of. I usually write that stuff myself .
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    assuming file is comma delimited as it appears and each line of file has same number of elements, then you can do something like this:

    Code:
    1)set up flag to be false
    
    2) use loop to read in first string from a line in file using the comma as a delimeter for either get() or getline() depending on your needs.
    
      a) compare first string of each line as it is read in for the desired data using strcmp() or one of it's cohorts if using C style strings or equal operator if using STL strings.
    
      b) if current string is desired value
          i) use loop to read in all subsequent strings on this line
          ii) set flag to true
    
      c) else if current string isn't desired value and flag is false
          i) use loop to read all subsequent strings but ignore them
      
      d) else if current string isn't desired value and flag is true
          i) use loop to read in all subsequent strings on this line
          ii) set flag to false

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM