Thread: reading text from a file

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    2

    reading text from a file

    Hello,

    I'm new to programming and I have a question about reading text from a file and I don't know how would be the best way to do it. For example I have a text file containing a few words or numbers placed in this way as below:

    4
    pears
    oranges
    apples
    bananas

    Now if I want to get only the word oranges out of it, which function should I use? Would it be better to read the characters into a 2D array? If I was to do that using say fgetch() how would I specify on which row the word oranges would begin?

    Thank you and I appreciate your help.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Start by reading each line with fgets().
    Then use various string comparison functions to determine what you read.
    Then perhaps use some kind of state (foundNumber, foundFruit) to keep track of where you are.
    Also perhaps a counter for how many fruit you've seen.
    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. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Reading Character at a time from a text file
    By Giania in forum C Programming
    Replies: 8
    Last Post: 02-25-2006, 03:17 PM
  5. A bunch of Linker Errors...
    By Junior89 in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2006, 02:59 PM